无法让我的播放器像我的鼠标一样在我的Python游戏中旋转

问题描述 投票:0回答:1

我已经阅读了所有相似的主题,但我找不到问题。我写了一个python游戏,我希望我的玩家通过方向箭头移动并通过鼠标旋转。

当我写关于旋转的代码时,我有退出错误:

Player对象没有属性position

我在互联网上尝试了许多不同的解决方案,但没有任何改变。

class Player(pygame.sprite.Sprite):
    #change_x = 0
    #change_y = 0

    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.image.load("player1.gif").convert()
        #self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.change_x = 0
        self.change_y = 0
        self.walls = None

    def changespeed(self, x, y):
        self.change_x += x
        self.change_y += y

    def move(self, walls):
        self.rect.x += self.change_x
        block_hit_list = pygame.sprite.spritecollide(self, walls, False)
        for block in block_hit_list:
            if self.change_x > 0:
                self.rect.right = block.rect.left
            else:
                self.rect.left = block.rect.right
        self.rect.y += self.change_y
        block_hit_list = pygame.sprite.spritecollide(self, walls, False)
        for block in block_hit_list:
            if self.change_y > 0:
                self.rect.bottom = block.rect.top
            else:
                self.rect.top = block.rect.bottom

    def rotate(self):
        mouse_x, mouse_y = pygame.mouse.get_pos()
        rel_x, rel_y = mouse_x - self.rect.x, mouse_y - self.rect.y
        angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
        self.image = pygame.transform.rotate(self.image, int(angle))
        self.rect = self.image.get_rect(center=self.position)

添加旋转功能后,这是我的代码。故障在哪里以及如何在主循环中调用旋转?

python pygame pycharm
1个回答
1
投票

可以通过pygame.Surface旋转图像(pygame.transform.rotate)。 如果逐步完成图像,则图像变形并快速增加。查看How do I rotate an image around its center using Pygame?的答案

要解决这个问题,你必须保留原始图像,并在类.image的构造函数中分配Player属性的副本:

self.image_source = pygame.image.load("player1.gif").convert()
self.image = self.image_source.copy()

旋转原始图像,并在方法.image中更新属性rotate

self.image = pygame.transform.rotate(self.image_source, int(angle))
self.rect = self.image.get_rect(center=self.rect.center)
class Player(pygame.sprite.Sprite):

    def __init__(self, x, y):
        super().__init__()

        self.image_source = pygame.image.load("player1.gif").convert()
        self.image = self.image_source.copy()
        self.rect = self.image.get_rect()
        self.rect.y = y
        self.rect.x = x
        self.change_x = 0
        self.change_y = 0
        self.walls = None

    def rotate(self):
        mouse_x, mouse_y = pygame.mouse.get_pos()
        rel_x, rel_y = mouse_x - self.rect.x, mouse_y - self.rect.y
        angle = (180 / math.pi) * -math.atan2(rel_y, rel_x)
        self.image = pygame.transform.rotate(self.image_source, int(angle))
        self.rect = self.image.get_rect(center=self.rect.center)
© www.soinside.com 2019 - 2024. All rights reserved.