慕工程0101907
2021-06-15 17:18:44
我很難使用 pygame 創(chuàng)建單個(gè)精靈旋轉(zhuǎn)。我正在按照此代碼(https://stackoverflow.com/a/47688650/5074998)獲取精靈的中心旋轉(zhuǎn)。這是我當(dāng)前的代碼: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()但我不明白為什么我會(huì)得到這個(gè):
1 回答

叮當(dāng)貓咪
TA貢獻(xiàn)1776條經(jīng)驗(yàn) 獲得超12個(gè)贊
發(fā)生這種情況是因?yàn)槟?code>self.image在位置[100, 100]
而不是self.rect
(這意味著在self.rect.topleft
坐標(biāo)處)進(jìn)行blitting 。每次旋轉(zhuǎn)后圖像的大小都不同,如果您只是在相同的左上角坐標(biāo)處對(duì)其進(jìn)行 blit,則圖像會(huì)像這樣擺動(dòng),因?yàn)槊恳粠闹行亩荚谄渌胤?。您可以通過(guò)在[100, 100]
以下位置繪制邊界矩形來(lái)看到:
pygame.draw.rect(screen, (255, 0, 0), [(100, 100), self.image.get_size()], 1)
為了解決這個(gè)問(wèn)題,你必須每次都創(chuàng)建一個(gè)新的矩形并將其center
坐標(biāo)設(shè)置center
為前一個(gè)矩形的坐標(biāo)。這也將調(diào)整topleft
坐標(biāo)(圖像被 blit 的位置),以便圖像保持居中。然后在 rect 處 blit 圖像:
screen.blit(self.image, self.rect)
繪制self.rect
以查看topleft
坐標(biāo)如何一直變化而中心不會(huì)移動(dòng):
pygame.draw.rect(screen, (255, 0, 0), self.rect, 1)
添加回答
舉報(bào)
0/150
提交
取消