Sin and Cos function incorrect in python [duplicate]

﹥>﹥吖頭↗ 提交于 2020-06-17 15:42:09

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/28780695/sin-and-cos-function-incorrect-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!