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