Player movement question (Unity3D)

Hi there, so I have a simple Unity 3D Player Movement Script. It works well, I can go left, right, forward, back etc. I also have a first person script for looking around which also works well, but some problems arise when I turn around and try use the player movement script. Everything seems to go inversed (Example, forward brings you backwards, vice versa) I was wondering if there was a problem with my code or a simple fix. All the best!

void FixedUpdate ()
    {
    	if (rb.velocity.y == 0)
    	isGrounded = true;

    	if (rb.velocity.y > 0.1)
    	isGrounded = false;

        if (Input.GetKey(KeyCode.W))
   	    rb.AddForce (Vector3.forward * MoveSpeed);

   	    if (Input.GetKey(KeyCode.S))
   	    rb.AddForce (Vector3.back * MoveSpeed);

   	    if (Input.GetKey(KeyCode.D)) 
   	    rb.AddForce (Vector3.right * MoveSpeed);

   	    if (Input.GetKey(KeyCode.A)) 
   	    rb.AddForce (Vector3.left * MoveSpeed);

   	    if (Input.GetKeyDown(KeyCode.Space)) 
   	    rb.AddForce (Vector3.up * JumpForce);
    }
}

This is because you are using the world coordinate system. You can think of it this way: You are sitting in a car and you are driving in the z direction. Your head is facing forward and everything is fine. When you look out of the left window, do you expect the car to go that way too? Nope, its still heading in the z direction. That is what your code is doing too.


What you NEED, is that the body move relative to the heads coordinate system. So if you look out of the left window, and hit the gas, the car should go sideways, how stupid that may sound :stuck_out_tongue: You can achieve this by using transform.TransformDirection(). Simple example:

Transform head;
Rigidbody body;

body.AddForce(head.TransformDirection(Vector3.forward * moveSpeed);

You should check out these pages:

Hope this gets you moving the right way!

You could try using transform.forward, transform.up, etc instead of the Vector3 ones.

That should take the local directions instead of the global ones.