The isssue is caused, because the pygame.Rect operates with integral data:
The coordinates for Rect objects are all integers. [...]
When you do
player.rect.x += player.xVel
it is the same as you would do:
player.rect.x = int(player.rect.x + player.xVel)
The fraction part of player.xVel
gets lost. The result of the addition operation is truncated and the player tends to the coordinate with the lower value (left).
Add a floating point x coordinate (self.px
) to the class Player
and use it to calculate the position of the player. Use round to set the integral rectangle position from self.px
:
class Player(pygame.sprite.Sprite):
def __init__(self):
# [...]
# Set a referance to the image rect.
self.rect = self.image.get_rect()
self.px = self.rect.x
# [...]
def update(self):
# [...]
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False)
for block in block_hit_list:
# If we are moving right,
# set our right side to the left side of the item we hit
if self.xVel > 0:
self.rect.right = block.rect.left
elif self.xVel < 0:
# Otherwise if we are moving left, do the opposite.
self.rect.left = block.rect.right
self.px = self.rect.x
def main():
# [...]
player.rect.x = 340
player.px = player.rect.x
# [...]
while not done:
# [...]
player.px += player.xVel
player.rect.x = round(player.px)
# [...]