Move player relative to camera rotation in 2D game
I am making a 2D game where the camera spins around with the player's rotation (so the z rotation of the camera and the player is always equal). I have been trying to get the player to move relative to the camera, so pressing up will always move it towards the top of the screen. I have seen plenty of fixes for this, but they are all for 3D games and I can't use anything involving a Vector3 or the Vector3.forward command because everything is in the x-y plane with Vector2s. I have tried using the angle of the camera's z rotation and putting into the following code that I got from the answer to a similar question but it didn't work at all:
Vector2 Vector2FromAngle(float a)
{
a *= Mathf.Deg2Rad;
return new Vector2(Mathf.Cos(a), Mathf.Sin(a));
}
I tried using the above code on just the camera's angle, on the camera's angle made negative, and on the camera angle plus the result of Vector2.Angle(from, movement)
where from was (0f, 1f) and then using the resulting Vector2 for movement. Nothing so far has worked. My movement code is
//If the camera is rotated, move according to what the camera calls up
if (cameraRotation != 0f && movement != new Vector2 (0f, 0f))
{
rb2d.AddForce(angleAdjust * speed);
}
//Otherwise, just use the basic axes
else if (cameraRotation == 0f && movement != new Vector2(0f, 0f))
{
rb2d.AddForce(movement * speed);
}
Where angleAdjust is the result of Vector2FromAngle using the sum of the rotation of the camera and the angle from the movement vector and movement is using the horizontal and vertical axes. I can't think of anything else that I could possibly do without changing the game to 3D and starting over. What can I do to make movement relative while still keeping the game 2D? Any suggestions are appreciated! Thank you!
Answer by love_and_lucky · Apr 20, 2016 at 05:42 PM
Fixed! It's actually a really simple solution - my entire movement code is now just
`void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
rb2d.AddRelativeForce(movement * speed);
}`
I don't even need to factor in the camera's rotation. It works perfectly no matter what the rotation is.