Question

I'm using the following code to move the camera in whatever direction it is facing. It is working fine.

public class moveCam : MonoBehaviour {

    public float walkSpeed = 0.9f;

    void Start () {
    }

    void Update () {
        //Walk In Direction Of Camera
        transform.position += transform.forward * walkSpeed * Time.deltaTime;
    }
}

The only problem I want to restrict my camera to ground level(i.e a constant position at Y), the work around for this is negate the calculate Y by resetting it, for which I am doing this

void Update () {
    //Walk In Direction Of Camera
    transform.position += transform.forward * walkSpeed * Time.deltaTime;
    transform.position = new Vector3(transform.position.x,0.7f,transform.position.z);
}

what I want to know is, Is there a better way to achieve this.

Was it helpful?

Solution

Just reset the Y position after the change like the following

void Update(){  
    //Code to move in any particular direction
    transform.position = new Vector3(transform.position.x,FIXED_Y_VALUE,transform.position.z);
}

or don't change Y direction at all -

void Update(){    
        Vector3 newCameraPosition = transform.position + transform.forward * walkSpeed * Time.deltaTime;  
        transform.position = new Vector3(newCameraPosition.x,transform.position.y,newCameraPosition.z);  
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top