Im making movement for my camera in unity. The starting position for my camera is 0,0,0. When i press the W key the code i take the current position and multiply it by a movement speed and equal it to another vector 3 to then update the postion of the position of the camera. It works great but i cant understand why when i think about.
If my camera is initialised at 0,0,0 then why does transform.forward * movementSpeed not always eqaul 0? This is the same for all directions i just used W as an example
Any help would be greatly appreciated as im new to unity. Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
private Vector3 newPosition;
[SerializeField] private float movementSpeed;
[SerializeField] private float movementTime;
// Start is called before the first frame update
void Start()
{
newPosition = transform.position;
Debug.Log(transform.position); //prints 0.0,0.0,0.0
Debug.Log(transform.forward * movementSpeed); //prints 0.0,0.0,0.3
}
// Update is called once per frame
void Update()
{
handleKeyboardInput();
}
void handleKeyboardInput()
{
if (Input.GetKey(KeyCode.W))
{
newPosition += (transform.forward * movementSpeed);
}
if (Input.GetKey(KeyCode.A))
{
newPosition += (transform.right * -movementSpeed);
}
if (Input.GetKey(KeyCode.S))
{
newPosition += (transform.forward * -movementSpeed);
}
if (Input.GetKey(KeyCode.D))
{
newPosition += (transform.right * movementSpeed);
}
transform.position = Vector3.Lerp(transform.position, newPosition, Time.deltaTime * movementTime);
}
}
The reason your code works is becuase transform.forward
and transform.right
refer to the forward and right directions of you player. When you add transform.forward * speed
to your newPosition
, you are adding the forward direction of the player but with a magnitude (length) of your speed.
If you want to try to understand it better, you can use print(transform.forward)
or print(transform.forward * speed)
or do Debug.drawRay(transform.position, transform.forward)