- Home /
Simple moving Cam in direction its facing
I need to move my cam in the direction its faceing. It should be simple I don`t need velocity, speed etc.
I imagine somthing like this:
if(Input.GetKey("w")){ moveDirection=transform.forward; }
if(Input.GetKey("s")){ moveDirection=transform.forward*-1; }
Answer by Vonni · Jan 04, 2013 at 09:51 PM
var moveSpeed : float = 20.0;
function Update(){
if(Input.GetKey(KeyCode.W)){
transform.localPosition.z += moveSpeed * Time.deltaTime;
}
if(Input.GetKey(KeyCode.S)){
transform.localPosition.z -= moveSpeed * Time.deltaTime;
}
}
Answer by maleone0487 · Aug 08, 2013 at 08:17 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613090356im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Simple move script 0 Answers
How to move the camera depending on the score? 1 Answer
Moving two objects and avoiding overlap with each other 1 Answer
3rd person player 0 Answers
Camera not moving on mobile 0 Answers