简体   繁体   English

pygame.transform.rotate不起作用

[英]pygame.transform.rotate not working

The code below is a draw function of an npc class in a game I'm making in pygame (source: https://github.com/hailfire006/games/blob/master/strategy%20gamev2 ), and it all works great except for this one line 下面的代码是我在pygame中制作的游戏中npc类的绘制函数(源: https : //github.com/hailfire006/games/blob/master/strategy%20gamev2 ),并且除以下各项外,其他所有功能都很好对于这一行

pygame.transform.rotate(self.sprite.image,angle)

which should rotate the npc towards the point it's moving to. 这应该将npc旋转到它要移动的点。 For whatever reason, it's just not rotating. 无论出于什么原因,它都没有旋转。 I think it might have something to do with the fact that I'm not storing the result of this function into a variable but I'm not sure. 我认为这可能与以下事实有关:我没有将此函数的结果存储到变量中,但不确定。

the rest of the function: 其余功能:

    target = get_target(self)
    if target != 0:
        angle = math.degrees(math.atan2(self.x - target[0], self.y - target[1])) + 90
        self.sprite.image = pygame.transform.rotate(self.sprite.image,angle)
        self.shoot(target)
    if self.moving != False:
        if abs(self.x - self.moving[0]) < 3 and abs(self.y - self.moving[1]) < 3:
            self.moving = False
        else:
            self.move(self.moving)
            if target == 0:
                angle = math.degrees(math.atan2(self.x - self.moving[0], self.y - self.moving[1])) + 90
                pygame.transform.rotate(self.sprite.image,angle)
    if self.hp <= 0:
        objects.remove(self)
        return

    self.sprite.rect = self.sprite.image.get_rect()
    self.sprite.rect.topleft = [self.x - 20, self.y - 20]
    window.blit(self.sprite.image, self.sprite.rect)

You need to have a self._base_sprite and a self._active_sprite 您需要具有一个self._base_sprite和一个self._active_sprite

Set your init code to initialise _base_sprite and then change your line from: 设置您的init代码以初始化_base_sprite ,然后从以下位置更改行:

pygame.transform.rotate(self.sprite.image,angle)

to: 至:

self._active_sprite = pygame.transform.rotate(self._base_sprite.image,angle)

and then blit your active sprite 然后把你活跃的精灵

The reasoning is: 原因是:

  • When rotating a sprite you buffer out the image so you don't lose pixels (including any alpha'd corners), which gains space 旋转精灵时,您可以缓冲图像,以免丢失像素(包括任何带有alpha角的角),从而获得空间
  • If you rotate a rotated sprite you repeat this process 如果旋转旋转的精灵,请重复此过程
  • If you keep rotating you will run out of memory 如果继续旋转,将耗尽内存
  • Thus, we retain two surfaces in memory, one "base" one and one "active" one. 因此,我们在内存中保留了两个表面,一个为“基础”,一个为“活动”。

Additionally, your .rect adjustment code should probably be only done in your init function. 此外,您的.rect调整代码可能应该仅在init函数中完成。 You're trying to adjust the center of the sprite, I assume? 我想您正在尝试调整精灵的中心?

Edit: Note, this question here is highly related (and in the sidebar). 编辑:请注意, 这里的问题是高度相关的(并在边栏中)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM