Search code examples
c#unity-game-enginetranslatecoordinate-transformation

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:

enter image description here

And since the camera object is rotated, in world space we have:

enter image description here

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!


Solution

  • It's not really clear what you're saying.

    But a very common thing is:

    Simply have a holder object. If you want, perhaps think of it as a "camera car". Keep that one "square" at all times, and move it around. Then, have the camera as a child of that object.

    You can then rotate (or whatever it is you are doing) the child object. When you want the "pure" motion, you can move the "holder" object.

    It is extremely common, almost inevitable, to do this in Unity.

    Again I have no clue what you're asking :) but hopefully this solves the problem.


    One more thing: it's possible you mean you want the user to move the object around, but, the object always stays on the ground. If that's what you mean, one approach is this: simply force the world z position to be zero, at the end of every frame (that is to say, by adding a line of code in your Update). It's pretty common to do that and it will get you going. Alternately if you're using Rigidbody, you'll be pleased to know there's literally a checkbox selector in the Inspector for constraining movement on the various axes.