如何使播放器向鼠标位置旋转?[重复]

如何使播放器向鼠标位置旋转?[重复],第1张

如何使播放器向鼠标位置旋转?[重复]

您想做什么取决于播放器的哪一部分(顶部或右侧等)应对准鼠标。

不要计算和求和相对角度。计算玩家到鼠标的向量

player_x, player_y = # position of the playermouse_x, mouse_y   = pygame.mouse.get_pos()dir_x, dir_y = mouse_x - player_x, mouse_y - player_y

向量的角度可以通过计算

math.atan2
。必须相对于玩家的基本方位计算角度。

例如

播放器的右侧面向鼠标:

angle = (180 / math.pi) * math.atan2(-dir_y, dir_x)

播放器的顶部朝向鼠标:

angle = (180 / math.pi) * math.atan2(-dir_x, -dir_y)

可以使用校正角度设置基本对齐方式。例如,对于一名在右上角观看的玩家,为45:

angle = (180 / math.pi) * math.atan2(-dir_y, dir_x) - 45

该方法

update
可能如下所示:

def update(self):    self.pos += self.vel * self.game.dt    mouse_x, mouse_y = pygame.mouse.get_pos()    player_x, player_y = self.pos    dir_x, dir_y = mouse_x - player_x, mouse_y - player_y    #self.rot = (180 / math.pi) * math.atan2(-dir_y, dir_x)    #self.rot = (180 / math.pi) * math.atan2(-dir_y, dir_x) - 45    self.rot = (180 / math.pi) * math.atan2(-dir_x, -dir_y)    self.image = pygame.transform.rotate(self.game.player_img, self.rot)    self.rect = self.image.get_rect()    self.rect.center = self.pos

最小示例:

[![](https://i.stack.imgur.com/5jD0C.png) repl.it/@Rabbid76/PyGame-RotateWithMouse](https://repl.it/@Rabbid76/PyGame-RotateWithMouse#main.py)



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5668512.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存