im making a Pygame game, and I want to move one sprite from the middle to the left, and when it reaches a limit move to the right, and viceversa.
class ColorLineCursor(Generic):
def __init__(self, position: tuple, surface: pygame.Surface, line_width, *groups: pygame.sprite.Group,
z=LAYERS["MAIN"]):
super().__init__(position, surface, *groups, z=z)
self.image = surface
self.rect = self.image.get_rect(center=position)
self.hitbox = self.rect.copy().inflate(-30, -10)
self.direction = "right"
self.origin = position
self.pathLenght = line_width
self.leftLimit = self.origin[0] - self.pathLenght / 2
self.rightLimit = self.origin[0] + self.pathLenght / 2
self.animationSpeed = 1
print(f"Origin: {self.origin} Left: {self.leftLimit}, Right: {self.rightLimit} ")
def animate(self, dt: float):
if self.direction == "left":
if self.rect.x <= self.leftLimit:
self.direction = "right"
else:
self.rect.x -= self.animationSpeed * dt
else:
if self.rect.x >= self.rightLimit:
self.direction = "left"
else:
self.rect.x += self.animationSpeed * dt
But i get an error trying to update the sprite and moving it exclusively to the right, I tought it was an float addition error, but I made an isolated test when the same values, and it works, so I dont know what Im making wrong.
direction = "left"
origin = 640
x = 640
length = 256
leftlimit = origin - length / 2
rightlimit = origin + length / 2
animationSpeed = 1
while True:
if direction == "left":
if x <= leftlimit:
direction = "right"
else:
x -= animationSpeed * 0.002
else:
if x >= rightlimit:
direction = "left"
else:
x += animationSpeed * 0.002
The code works only if I remove the dt in the "right" movement, but in the "left" movement works fine