- Home /
Move camera along 2 axes in WorldSpace
I have a camera which I want to move along 2 axes (x and z). In local space we have:
And since the camera object is rotated, in world space we have:
What I want to achieve is: to move the camera along 2 axes via user input - the camera is looking at the plane from above and by pressing keyboard buttons, the user can slide along the plane in 4 flat directions. This works perfectly by manipulating the transform.position.x and transform.position.y properties in local space.
I have the following problem though: the user can also rotate the camera object. By doing so, I can no longer manipulate the local space transform, since at certain rotations "up" begins to mean "down" and etc.
I have tried doing the following in world space:
transform.Translate(transform.right * user_input, Space.World);
But this does not achieve what I want since transform.right grabs the red vector in world space.
What I want to do is: move the camera along the red and blue vectors in local space, but still preserve the coordinates in world space.
I'd be grateful if someone provided some input on this. Thanks a bunch!
Answer by Drayan · Sep 01, 2016 at 08:37 AM
You can simply use the eulerAngles.y of the camera transform. This way you only have the rotation around the Y axis, then you apply the same rotation to the movement vector.
var camForwardAngle = Camera.main.transform.eulerAngles.y;
var moveVector = Quaternion.Euler(new Vector3(0, camForwardAngle, 0)) *
new Vector3 (xAmount, 0, zAmount);
In case someone is interested ;)
Answer by revolute · Jan 15, 2016 at 03:05 AM
If you mean that up arrow key is simply moving camera in its facing direction, try transform.forward.
Transform.forward will always give you forward vector, meaning that for cameras, forward vector would be the direction the camera is looking at.
Combine transform.forward with your input and the camera would move forward whenever you press the right key.
eg:
void Update(){
transform.position = transform.forward * speed * Time.deltaTime + transform.position;
}
this code would simply move the object forwards.
Thanks a bunch for the response. Transform.forward didn't work for me because I didn't want the camera to move in the direction it was looking at (as shown in the second screenshot of my post - the camera is looking at the plane in world space, hence the forward vector is pointing at the plane). I wanted to move the camera parallel to the plane (as shown in the first screenshot - the "forward vector" is parallel to the plane, but it's in local space).
I ended up using an empty container game object as a parent to my camera. That way I can move the container game object in world space, achieving the desired camera movement.