# How do you move the camera relative to the direction it is currently facing?

Sorry if the question doesn’t make much sense, but I hope I can explain my dilemma a bit better. First off, I’m not very experienced with Unity, or coding for that matter so for all I know the answer could be super simple.

Alright, so I have my code set up so I can move the camera along the X and Z axis by holding down the right mouse button and dragging. I also have the ability to rotate the camera on the Y axis by holding down the scroll wheel and dragging.

The problem I am having, is that when I rotate the camera something like 90 degrees, and I right click to move the camera it still moves in the same way (if that makes sense). So dragging the mouse horizontally moves the camera forward and backward along the X, while dragging vertically moves it left and right along the Z. So the camera always moves the same way, and not relative to which way it is facing.

Here’s the code I have been using:

``````var xPosition : float;
var zPosition : float;
var yRotation : float;
var currentYRotation : float;
var currentXPosition : float;
var currentZPosition : float;
var yRotationV : float;
var xPositionV : float;
var zPositionV : float;
var moveSensitivity : float = 3;
var lookSmoothDamp : float = 0.1;

function Update ()
{
if(Input.GetMouseButton(1))
{
zPosition -= Input.GetAxis("Mouse Y") * moveSensitivity;
xPosition -= Input.GetAxis("Mouse X") * moveSensitivity;

currentXPosition = Mathf.SmoothDamp(currentXPosition, xPosition,       xPositionV, lookSmoothDamp);
currentZPosition = Mathf.SmoothDamp(currentZPosition, zPosition, zPositionV, lookSmoothDamp);

transform.position = Vector3(xPosition, 0, zPosition);
}

if(Input.GetMouseButton(2))
{
yRotation -= Input.GetAxis("Mouse X") * moveSensitivity;

currentYRotation = Mathf.SmoothDamp(currentYRotation, yRotation,   yRotationV, lookSmoothDamp);

transform.rotation = Quaternion.Euler(0, yRotation, 0);
}
}
``````

I actually have the camera attached to an empty game object which has the actual script attached to it, so I didn’t know if it was possible to move the camera based on the position of the empty game object instead of world position. Though I don’t even know if that would solve the problem.

All Transform components have forward, right, and up vector that is relative.

The forward property is a Vector3 that points in the local Z direction. Up points in local Y, and right in local X. Obviously to get down you use -up.

So, to move something “forward” (assuming “forward” means “into the Z direction”), you can do:

``````transform.position += transform.forward * distance;
``````

If that’s forward, then to move to the right:

``````transform.position += transform.right * distance;
``````

Left is:

``````transform.position += -transform.right * distance;
``````