1 回答

TA貢獻1757條經驗 獲得超7個贊
由于pygame.Rect
應該代表屏幕上的一個區域,一個pygame.Rect
對象只能存儲整數數據:
Rect 對象的坐標都是整數。[...]
如果要以浮點精度存儲對象位置,則必須將對象的位置分別存儲在單獨的變量和屬性中,并同步對象pygame.Rect
。round
坐標并將其分配給.topleft
矩形的位置(例如):
x,?y?=?#?floating?point?coordinates rect.topleft?=?round(x),?round(y)
因此(x, y)
是準確的位置并且(rect.x, rect.y)
包含最接近該位置的整數。
請參見以下示例。紅色物體是通過直接改變物體的位置來移動的pygame.Rect
,而綠色物體的位置存儲在單獨的屬性中,移動是用浮點精度計算的。你可以清楚地看到紅色物體在方向和速度方面的不準確:
import pygame
class RedObject(pygame.sprite.Sprite):
? ? def __init__(self, p, t):
? ? ? ? super().__init__()
? ? ? ? self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
? ? ? ? pygame.draw.circle(self.image, "red", (10, 10), 10)
? ? ? ? self.rect = self.image.get_rect(center = p)
? ? ? ? self.move = (pygame.math.Vector2(t) - p).normalize()
? ? def update(self, window_rect):
? ? ? ? self.rect.centerx += self.move.x * 2
? ? ? ? self.rect.centery += self.move.y * 2
? ? ? ? if not window_rect.colliderect(self.rect):
? ? ? ? ? ? self.kill()
class GreenObject(pygame.sprite.Sprite):
? ? def __init__(self, p, t):
? ? ? ? super().__init__()
? ? ? ? self.image = pygame.Surface((20, 20), pygame.SRCALPHA)
? ? ? ? pygame.draw.circle(self.image, "green", (10, 10), 10)
? ? ? ? self.rect = self.image.get_rect(center = p)
? ? ? ? self.pos = pygame.math.Vector2(self.rect.center)
? ? ? ? self.move = (pygame.math.Vector2(t) - p).normalize()
? ? def update(self, window_rect):
? ? ? ? self.pos += self.move * 2
? ? ? ? self.rect.center = round(self.pos.x), round(self.pos.y)
? ? ? ? if not window_rect.colliderect(self.rect):
? ? ? ? ? ? self.kill()
pygame.init()
window = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
start_pos = (200, 200)
all_sprites = pygame.sprite.Group()
run = True
while run:
? ? clock.tick(100)
? ? for event in pygame.event.get():
? ? ? ? if event.type == pygame.QUIT:
? ? ? ? ? ? run = False
? ? ? ? if event.type == pygame.MOUSEBUTTONDOWN:
? ? ? ? ? ? all_sprites.add(RedObject(start_pos, event.pos))
? ? ? ? ? ? all_sprites.add(GreenObject(start_pos, event.pos))
? ? all_sprites.update(window.get_rect())
? ? window.fill(0)
? ? all_sprites.draw(window)
? ? pygame.draw.circle(window, "white", start_pos, 10)
? ? pygame.draw.line(window, "white", start_pos, pygame.mouse.get_pos())
? ? pygame.display.flip()
pygame.quit()
exit()
添加回答
舉報