为了账号安全,请及时绑定邮箱和手机立即绑定

如何使这个 pygame 精灵的旋转(以中心为中心)起作用?

如何使这个 pygame 精灵的旋转(以中心为中心)起作用?

慕工程0101907 2021-06-15 17:18:44
我很难使用 pygame 创建单个精灵旋转。我正在按照此代码(https://stackoverflow.com/a/47688650/5074998)获取精灵的中心旋转。这是我当前的代码:import pygameFPS: int = 100W = 600H = 400MAGENTA = (255, 0, 255)BLACK = (0, 0, 0)pygame.init()screen = pygame.display.set_mode([W, H])pygame.display.set_caption("Cars")clock = pygame.time.Clock()class sp():    def __init__(self):        self.image = pygame.Surface((122, 70), pygame.SRCALPHA)        pygame.draw.polygon(self.image, pygame.Color('dodgerblue1'),                            ((1, 0), (120, 35), (1, 70)))        self.orig_image = self.image        self.rect = self.image.get_rect(center=[W / 2, H / 2])        self.angle = 0    def update(self):        self.angle += 2        self.rotate()        screen.blit(self.image, [100, 100])    def rotate(self):        self.image = pygame.transform.rotozoom(self.orig_image, self.angle, 1)        self.rect = self.image.get_rect(center=self.rect.center)sp1 = sp()out = pause = Falsewhile not out:    clock.tick(FPS)    for event in pygame.event.get():        if event.type == pygame.QUIT or event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:            out = True        if event.type == pygame.KEYDOWN:            if event.key == pygame.K_SPACE:                pause = not pause    if not pause:        screen.fill(BLACK)        sp1.update()        pygame.display.flip()但我不明白为什么我会得到这个:
查看完整描述

1 回答

?
叮当猫咪

TA贡献1776条经验 获得超12个赞

发生这种情况是因为您self.image在位置[100, 100]而不是self.rect(这意味着在self.rect.topleft坐标处)进行blitting 。每次旋转后图像的大小都不同,如果您只是在相同的左上角坐标处对其进行 blit,则图像会像这样摆动,因为每一帧的中心都在其他地方。您可以通过在[100, 100]以下位置绘制边界矩形来看到:

pygame.draw.rect(screen, (255, 0, 0), [(100, 100), self.image.get_size()], 1)

为了解决这个问题,你必须每次都创建一个新的矩形并将其center坐标设置center为前一个矩形的坐标。这也将调整topleft坐标(图像被 blit 的位置),以便图像保持居中。然后在 rect 处 blit 图像:

screen.blit(self.image, self.rect)

绘制self.rect以查看topleft坐标如何一直变化而中心不会移动:

pygame.draw.rect(screen, (255, 0, 0), self.rect, 1)


查看完整回答
反对 回复 2021-06-22
  • 1 回答
  • 0 关注
  • 453 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号