Pygame 精灵没有相应地转向鼠标

Pygame sprite not turning accordingly to mouse

我一直在尝试,但基本上我想做一个坦克游戏,有一个可以通过鼠标转动自己发射子弹的坦克;当您将鼠标转向某个方向时,精灵将完全跟随。问题是,无论如何我都无法用任何代码转动坦克。

import os
import pygame
import math

pygame.init()
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 30)
icon = pygame.image.load('Sprite3.png')
pygame.display.set_icon((icon))
pygame.display.set_caption('DeMass.io')

class Tank(object):  # represents the bird, not the game
    def __init__(self):
        """ The constructor of the class """
        self.image = pygame.image.load('Sprite0.png')
        # the bird's position
        self.x = 0
        self.y = 0

    def handle_keys(self):
        """ Handles Keys """
        key = pygame.key.get_pressed()
        dist = 1
        if key[pygame.K_DOWN] or key[pygame.K_s]:
            self.y += dist # move down

        elif key[pygame.K_UP] or key[pygame.K_w]:
            self.y -= dist # move up

        if key[pygame.K_RIGHT] or key[pygame.K_d]:
            self.x += dist # move right

        elif key[pygame.K_LEFT] or key[pygame.K_a]:
            self.x -= dist # move left


def draw(self, surface):
        """ Draw on surface """
        # blit yourself at your current position
        surface.blit(self.image, (self.x, self.y))

w = 1900
h = 10000
screen = pygame.display.set_mode((w, h))

tank = Tank() # create an instance
clock = pygame.time.Clock()
connection_angle = 90

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit() # quit the screen
            running = False
    
    
    screen.fill((255, 255, 255))  
    tank.draw(screen)  
    pygame.display.update()  
    tank.handle_keys() 
    clock.tick(100)

您可以使用内置 math 模块中的 atan2 函数来计算两个坐标之间的角度, 然后相应地旋转你的精灵:

import pygame
from math import atan2, degrees

wn = pygame.display.set_mode((400, 400))

class Player(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((30, 40), pygame.SRCALPHA)
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect(topleft=(185, 180))

    def point_at(self, x, y):
        rotated_image = pygame.transform.rotate(self.image, degrees(atan2(x-self.rect.x, y-self.rect.y)))
        new_rect = rotated_image.get_rect(center=self.rect.center)
        wn.fill((0, 0, 0))
        wn.blit(rotated_image, new_rect.topleft)

player = Player()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
        elif event.type == pygame.MOUSEMOTION:
            player.point_at(*pygame.mouse.get_pos())

    pygame.display.update()

输出: