Top down 2d movement without being affected by rotation

Hey guys,

Currently i am working with Unity 4.13 using the new 2d features to make a top down 2d adventure game in the style of games like the 2d Zelda’s. Currently i have it so the player rotates to face the mouse but is locked to the 90 degree angles (up, down, left, right) and no others. My issue is when the rotation is changed (it’s the z axis that i am changing) the movement no longer stays the same. For example when the rotation is 0 (the default, facing up) the player moves in the correct direction, up is up, left is left and so on. But when the rotation changes the player directions get messed up and up becomes down and left becomes right, or up becomes left.

I have tried changing the transform.forward but i have gotten some really weird rotation bugs from that so i am pretty sure i did it wrong if that is the correct way to fix this.

Here is what i have for my movement and my rotation:

transform.position += transform.right * Input.GetAxis ("Horizontal") * speed * Time.deltaTime;
transform.position += transform.up * Input.GetAxis("Vertical") * speed * Time.deltaTime;

mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y, Camera.main.transform.position.y-transform.position.y);
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
playerRotPos = mousePos - transform.position;
angle = -Mathf.Atan2 (playerRotPos.y, playerRotPos.x) *Mathf.Rad2Deg + 0.0f;
angle = Mathf.Round(angle/90.0f) * 90.0f;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);

Any help would be great as i am stuck on this problem.
Thanks in advance. :slight_smile:

2 Answers

2

transform.right and transform.up are the local ‘up’ and ‘right’ relative to the game object. It seems to me you want world coordinates. Replace the first two lines:

transform.position += Vector3.right * Input.GetAxis ("Horizontal") * speed * Time.deltaTime;
transform.position += Vector3.up * Input.GetAxis("Vertical") * speed * Time.deltaTime;

Thank you so much for that. :)

Note: The “Best Answer” in this topic takes away all physics properties from the player game objects and won’t work properly with colliders.

How can i make without effecting the colliders and rotation ??