How do I rotate a game object and have it move in relation to the rotation angle?


I’m trying to make a rectangle turn and move, but when I move it, it moves in relation to the initial starting rotation, as opposed to the actual rotation of the object. Basically, if I rotate it 90 degrees to the right, it will still move around as if I had not done any rotation. I’m relatively new to Unity, so apologies if this is a really stupid question.

Here’s my code for movement (in C#):

 moveDirection.x -= 1;
 moveDirection.x += 1;
 moveDirection.y += 1;
 moveDirection.y -= 1;
 transform.Rotate(Vector3.up * Time.deltaTime);
 newPosition = moveDirection * (moveSpeed * Time.deltaTime);
 newPosition = transform.position + newPosition;
 transform.position = newPosition;

Where newPosition and moveDirection are vector3 variables, and moveSpeed is an integer variable.

What I want to happen is have the object this script is attached to move in relation to the current rotation, so if we were to look at this from a top-down, bird’s eye view, the box would move to the right if I rotated it 90 degrees so that it’s facing east, it would travel to the east, or if I rotated it so that it’s facing northwest, it would travel northwest, when the move forward key (W) is pressed.

As far as controls go, I’m using WSAD for forwards, backwards, left rotation, and right rotation, respectively.

I’d prefer to get help in the form of C# code, but I can probably translate anything provided in Javascript effectively. Thanks!

Use transform.forward. That’s the normalized Z-Axis vector of your current object.

Meaning; If you wanted to move forward by a meter:

<pre>transform.position = Input.GetAxis("Vertical") * transform.forward;</pre>

Hope that helps.

What I used (C#):

 //Move forwards and backwards
   moveDirection.x -= 1;
   moveDirection.x += 1;
 //Move up and down
   moveDirection.y += .5f;
   moveDirection.y -= .5f;
 //Turn left and right
   gameObject.transform.Rotate(0, 90 * Time.deltaTime, 0);
   gameObject.transform.Rotate(0, -90 * Time.deltaTime, 0);
 //Update position
 transform.position += moveDirection.x * transform.right;
 transform.position += moveDirection.y * transform.up;

transform.right was used instead of transform.forward because of the orientation of the model I was using.

moveDirection is a Vector3 declared within the update function. If anyone has questions or suggestions, do ask.