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()
添加回答
举报