2
votes

I'm creating a Google Cardboard VR app in Unity. I want the camera to constantly move forwards horizontally in the direction the camera is facing but not change its Y position, i.e. not rise or fall.

I've managed to get it so that the camera moves forwards in whichever direction it's looking but can go up and down if you look that way, using this line of code:

transform.position = transform.position + cam.transform.forward * WalkingSpeed * Time.deltaTime;

Is there a simple way of fixing the Y axis, so that I get the behaviour I'm looking for? Here's the full code so far:

using UnityEngine;
using System.Collections;

public class CameraMovement : MonoBehaviour {

    public float WalkingSpeed = 1.0f;
    public bool WalkEnabled = true;

    GameObject cam;

    void Start () {
        // This is the part of the Cardboard camera where I'm getting
        // the forward position from:
        cam = GameObject.FindWithTag("CCHead");
    }

    void Update () 
    {
        if (WalkEnabled) 
        {
            walk();
        }
    }

    void walk()
    {
        transform.localPosition = transform.localPosition + cam.transform.forward * WalkingSpeed * Time.deltaTime;
    }
}

Note: ticking the 'freeze position' y value in rigidbody constraints doesn't work.

Many thanks in advance.

1

1 Answers

0
votes

You can try and split the forward vector up and build a new one where the y axis does not change:

 transform.position =  
 transform.position + 
 new Vector3(
      cam.transform.forward.x * WalkingSpeed * Time.deltaTime,
      0, // add 0 to keep the y coordinate the same
      cam.transform.forward.z * WalkingSpeed * Time.deltaTime);