0

I am trying to make a top down shooter in pygame. I when I added the code to make the player move in the direction they are facing. The player would move in weird directions. This is the code I am using:

        if pygame.key.get_pressed()[K_UP]:
            playerX = playerX - math.cos(playerFacing)
            playerY = playerY - math.sin(playerFacing)
        if pygame.key.get_pressed()[K_DOWN]:
            playerX = playerX + math.cos(playerFacing)
            playerY = playerY + math.sin(playerFacing)

I tried just typing in math.cos(90) and it equaled -0.299515394756 but my calculator is telling me it equals 0. I am probably just making a stupid mistake, but can anyone tell me what I am doing wrong. Thanks Xeno

Xeno Holdgate
  • 11
  • 1
  • 2
  • The math functions expect radians rather than degrees. Use `math.radians` to convert degrees to radians. – Dunes Feb 28 '15 at 10:36

2 Answers2

9

math.sin, math.cos, etc. take angles in radians.

You can use math.radians to convert degrees to radians. So:

math.sin(math.radians(90)) == 0

And you could just fix it in the posted snippet like that:

if pygame.key.get_pressed()[K_UP]:
            playerX = playerX - math.cos(math.radians(playerFacing))
            playerY = playerY - math.sin(math.radians(playerFacing))
        if pygame.key.get_pressed()[K_DOWN]:
            playerX = playerX + math.cos(math.radians(playerFacing))
            playerY = playerY + math.sin(math.radians(playerFacing))

However I advise to just use radians everywhere.

sbarzowski
  • 2,707
  • 1
  • 20
  • 25
0

math.sin() and math.cos() take angles in Radians and not in Degrees.

The same would be the case with numpy.sin() and numpy.cos()

>>> import math
>>> math.sin(90)
0.8939966636005579
>>> math.sin(1.57)
0.9999996829318346

You can see that math.sin(90) should be 1, but instead we get 0.89. But math.sin(1.57) gives us the correct answer, because 90 degrees is 1.57 in radians.

Here is a WEBSITE that explains you the conversion between radians<-->degrees.

Srivatsan
  • 9,225
  • 13
  • 58
  • 83