我在使用Python的三角函数时遇到问题。我在一个小型的自上而下的射手上工作,计算角度和旋转精灵的方式对我的玩家,我的子弹有效,但是对我的敌人(始终面对玩家)来说,这很奇怪。
当播放器静止时,它可以正常工作,但是一旦播放器移动(并且角度改变),敌人就会抖动到位,似乎每帧来回移动一两个像素。 我将调试打印保留在代码中,并将在“问题”期间附加一些控制台打印输出:
class Enemy:
def __init__(self, x, y,):
self.x = x
self.y = y
self.angle = 0
self.speed = 2
self.velX = 0
self.velY = 0
self.scoreVal = 10
self.texture = pygame.image.load('char_terrorist.png')
self.image = pygame.transform.rotate(self.texture, int(self.angle))
def rotate(self):
targetX, targetY = player1.x, player1.y
relX, relY = targetX - self.x, targetY - self.y
self.angle = (180 / math.pi) * math.atan2(relY, relX)
self.image = pygame.transform.rotate(self.texture, int(self.angle)*-1-90)
self.rect = self.image.get_rect(center=(self.x, self.y))
self.velX = self.speed * math.cos(self.angle)
self.velY = self.speed * math.sin(self.angle)
print()
print('## ROTATE: velX, velY: ', self.velX, self.velY)
print('## ROTATE ANGLE: ', self.angle)
def move(self):
print('## MOVE: velX: ', self.velX, ' velY: ', self.velY)
self.x += self.velX
self.y += self.velY
def render(self):
imageRect = self.image.get_rect()
imageRect.center = self.x, self.y
playSurface.blit(self.image, imageRect)
以及控制台打印输出的一部分:
## ROTATE: velX, velY: 1.5033760962079608 1.31903764667674
## ANGLE: -93.52760115485472
## MOVE: x, y: 158.34842803029636 374.5728764810448
## MOVE: velX, velY: 1.5033760962079608 1.31903764667674
## ROTATE: velX, velY: -0.15199863628529925 -1.9942157392236701
## ANGLE: -95.89464860414104
## MOVE: x, y: 158.19642939401106 372.5786607418211
## MOVE: velX, velY: -0.15199863628529925 -1.9942157392236701
## ROTATE: velX, velY: -1.6646141877222582 1.1086296072330768
## ANGLE: -97.97691175203515
## MOVE: x, y: 156.5318152062888 373.6872903490542
## MOVE: velX, velY: -1.6646141877222582 1.1086296072330768
## ROTATE: velX, velY: 1.2713600983706417 1.5439052756794998
## ANGLE: -99.64905773569804
## MOVE: x, y: 157.80317530465945 375.2311956247337
## MOVE: velX, velY: 1.2713600983706417 1.5439052756794998
## ROTATE: velX, velY: 0.47746450045160277 -1.9421708603540784
## ANGLE: -101.8607010982417
## MOVE: x, y: 158.28063980511104 373.28902476437963
## MOVE: velX, velY: 0.47746450045160277 -1.9421708603540784
## ROTATE: velX, velY: 1.743360387120541 0.9801502745084132
## ANGLE: -100.01878896583855
## MOVE: x, y: 160.02400019223157 374.269175038888
## MOVE: velX, velY: 1.743360387120541 0.9801502745084132
## ROTATE: velX, velY: -1.2224714556282295 1.5828971982331
## ANGLE: -98.30254758732487
## MOVE: x, y: 158.80152873660333 375.85207223712115
## MOVE: velX, velY: -1.2224714556282295 1.5828971982331
我注意到velX和velY的计算错误,但是角度似乎是正确的。我真的不知道该如何更好地调试它,我盯着角度算法有一段时间了,但是赢了没有正确的想法。
谢谢大家的帮助!
答案 0 :(得分:1)
我在评论中指出的原因是由于degree
和math.sin()
使用了math.cos()
。
因此只需将它们改回弧度即可解决问题。
self.velX = self.speed * math.cos(self.angle * (math.pi /180))
self.velY = self.speed * math.sin(self.angle * (math.pi /180))