造成此问题的原因是,pygame.Rect
存储整数坐标:
Rect对象的坐标都是整数。[…]
的部分组件dx
,并dy
当你丢失:
self.Rect.x += dx
self.Rect.y += dy
您必须以浮点精度进行计算。在类中添加一个x
andy
属性。递增属性move
并同步Rect
属性:
class Player:
def __init__(self, color):
self.Rect = pygame.Rect([50, 50], [30, 50])
self.x = self.Rect.x
self.y = slef.Rect.y
# [...]
def move(self, dx, dy, platforms):
# Test for collisions with platforms
# handle movement on the X axis
self.x += dx
self.Rect.x = round(self.x)
for platform in platforms:
if self.Rect.colliderect(platform.Rect):
if dx > 0:
self.Rect.right = platform.Rect.left
if dx < 0:
self.Rect.left = platform.Rect.right
self.x = self.Rect.x
# Reset veLocity when collision with wall
self.vx = 0
# handle movement on the Y axis
self.Rect.y += dy
self.Rect.y = round(self.y)
for platform in platforms:
if self.Rect.colliderect(platform.Rect):
if dy > 0:
self.Rect.bottom = platform.Rect.top
if dy < 0:
self.Rect.top = platform.Rect.bottom
self.y = self.Rect.y
# Reset veLocity when collision with floor or roof
self.vy = 0
# return correctly collided rect to draw()
return self.Rect