0
\$\begingroup\$

I'm currently writing the script for the player to explore the plane below. The camera view is set to be slightly rotated as to look down. And I have set the code to make the camera move.

This is the code, and everything is set in the update method.

        if (Input.GetKey("w"))
        {
            transform.Translate(Vector3.forward * panSpeed * Time.deltaTime);   // , Space.World if want to avoid camera going down
        }
        if (Input.GetKey("s"))
        {
            transform.Translate(Vector3.back * panSpeed * Time.deltaTime);
        }
        if (Input.GetKey("d"))
        {
            transform.Translate(Vector3.right * panSpeed * Time.deltaTime);
        }
        if (Input.GetKey("a"))
        {
            transform.Translate(Vector3.left * panSpeed * Time.deltaTime);
        }

View from Camera

The problem is that everytime that the camera goes forward, it goes straight down. And I don't want it to do that. I want to keep the "height" from the plane below to be the same as in the picture below. I want the camera to move along the red axis.

Axis of Camera

I know of the existence of Space.World in order to achieve this, but the problem is that if I do that, whenever I rotate, now the controllers are all screwed up, because if I rotate to the right for example. Now Forward (W) moves the camera to the left, Right (D), moves the camera forward, etc etc.

So basically what I need is 1: to make the camera keep the distance to the plane below while moving (not going down). and 2. To make it possible that even with rotations, the controllers are kept, and not having this weird behavior, when forward is not longer forward.

Any ideas how to achieve this?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

One way to do this would be to take the respective vector that you use (forward, backward, left and right) and only use the x and z coordinates, leaving y at 0.

Something along the lines of

Vector3 direction = new Vector3(transform.forward.x, 0, transform.forward.z);

Notice that it should be transform.forward as it will be forward relative to the object you are moving (the camera)

Edit: Finally you could normalize the vector after creating it in order to keep the same speed at all times

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .