Move player forward based on it's y rotation

I am currently working on a simple three person player movement which player moves based on its rotation. I able to get my camera facing player based on player’s rotation but I couldn’t get my player move based on the rotation it’s facing. I don’t want to use unity provide methods like transform.TransformDirection because I am trying to see how well I understand the trigonometry behind it.

The following is my code:

void thirdPersonMovement()
    {
   
        yRotation = transform.eulerAngles.y;
        float xMove = unitDistance * Mathf.Sin( yRotation * Mathf.Deg2Rad) * 0.01f;
        float zMove = unitDistance * Mathf.Cos( yRotation * Mathf.Deg2Rad) * 0.01f;

        Vector3 forwardVector = new Vector3(xMove, 0, zMove);
        Debug.Log(forwardVector);
        if(Input.GetKey(KeyCode.UpArrow))
            transform.Translate(forwardVector);
      
    }

Could someone guide me which part I did it in the wrong way?
Thanks.

Where is the problem? Are you getting any error ?
I made a quick test for the code. Seems to be working fine for me.

i have another three person camera which faces where the player is facing. when i am using the controller code, for example the player moves forward if the y rotation is 0 degree. However if I slightly rotate it to like 65 or bigger, the forward vector became weird. i am not sure if thats my camera problem but when i try to edit player rotation on scene editor it seems the weird thing didnt change.

Ok.
Try changing Translate’s 2nd parameter to Space.World.
May be that’s the issue you are talking about.

Hi. Thank you for your reply. I will try that when I reach home, don’t have computer on my hands now.
Just want to make sure one thing, is my calculation correct? I am trying to implement something like transform.forward to understand the math behind. But it seems like the math done in the following page is a little bit different
https://discussions.unity.com/t/694484

I will check the link later.
However I tested the code. And I see the gameObject moving at an angle, it’s rotated at. So calculations look fine in my opinion.
And using Space.World instead of Space.Self and vice versa does make difference in output.

1 Like

Hi, I tried it today and it works!
I believe my math done it right way. Thank you!

Your code is framerate-dependent, ie. the player will move faster at faster framerates.
You’re also using the euler angles of the transform, which isn’t very accurate. As @orionsyndrome is saying, just use your transform’s .forward vector, which is what you’re calculating, just faster and more convenient.

1 Like

transform.forward is literally the same thing as transform.rotation * Vector3.forward
only more convenient and, perhaps, faster.