您想做什么取决于播放器的哪一部分(顶部或右侧等)应对准鼠标。
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)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)