Camera Movement with WASD

Hello!

I was trying to get camera movement working using the WASD keys based off of the code Rick showed us in this lecture. I got it working pretty well using this code:

    void Update()
    {
        float xMove = Input.GetAxis("Horizontal");
        float zMove = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(xMove, 0.0f, zMove);
        Vector3 normalizedMovement = movement.normalized;
        Vector3 finalMovement = normalizedMovement * Time.deltaTime * moveSpeed;

        transform.Translate(finalMovement);
    }

The left and right movement (using A and D keys) works perfectly, but for some reason using the W and S keys causes both the Y and Z values of the camera’s transform.position to change. I don’t understand what is causing the Y value to change since I passed a value of 0 to Y.

I was able to fix this by changing the above code to:

    void Update()
    {
        float xMove = Input.GetAxis("Horizontal");
        float zMove = Input.GetAxis("Vertical");

        Vector3 movement = new Vector3(xMove, 0.0f, zMove);
        Vector3 normalizedMovement = movement.normalized;
        Vector3 finalMovement = normalizedMovement * Time.deltaTime * moveSpeed;

        transform.Translate(finalMovement);

        float xVal = transform.position.x;
        float zVal = transform.position.z;

        transform.position = new Vector3(xVal, cameraHeight, zVal);
    }

While this fixes the bug I had, it does not seem like a very elegant solution and I am still curious what the first set of code did not execute as expected. Any help would be greatly appreciated!

Thanks!
Bobby

Hi bobbygs,

Welcome to our community! :slight_smile:

What was the initial position of the camera? If its y-position was not 0.0f, the Translate method will also “move” the current y-position value towards 0.0f. This is just a guess, though, because in your fix, you override the y-position with cameraHeight, which seems to be the only relevant difference between the two versions.

What you could test is to replace 0.0f with cameraHeight. If that also fixes the problem, my guess was right.


See also:

Figured out the problem! I had the camera angled/rotated downwards, and it seems like the translate method by defaults uses relativeTo="Space.Self", which causes the object to move relative to its own axes rather than the worldspace’s axes.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms