The Previous answer does not account for the camera’s pitch (rotation around the x vector) which is common in games (top down camera, free rotate camera, over-the-shoulder third person camera, etc). In order to account for this, use the following code.
private void Update()
{
Vector3 movement = Vector3.zero;
Vector3 camEuler = Camera.rotation.eulerAngles;
camEuler.x = 0f;
Quaternion normalizedRotation = Quaternion.Euler(camEuler);
if (Input.GetKey(KeyCode.W))
{
movement += normalizedRotation * Vector3.forward;
}
if (Input.GetKey(KeyCode.S))
{
movement -= normalizedRotation * Vector3.forward;
}
if (Input.GetKey(KeyCode.A))
{
movement -= normalizedRotation * Vector3.right;
}
if (Input.GetKey(KeyCode.D))
{
movement += normalizedRotation * Vector3.right;
}
if (movement.magnitude > 1f)
{
movement = movement.normalized;
}
_charController.Move(movement * WalkSpeed * Time.deltaTime);
}
This snippet removes the pitch from the camera’s current rotation (zeroing out the x portion of the camera’s euler angle), making it level with the world. To transform this into a usable movement vector, multiply the resulting rotation (normalizedRotation) by whichever direction you want to move the object.