Why my object doesn't rotate continuously?

Viewed 39

Error : So, I'm having a logic error.

I want my object called 'Claw' rotate (range : 10-170 degrees) back and forth. But, somehow when Claw reached the angle of 170, the value of angle didn't decrease. It sticks at the angle of 170.

Here is my Claw class

class Claw(pygame.sprite.Sprite):
    
    def __init__(self,image,position):
       
        super().__init__()
        self.original_image = image #saved original image(unchangeable)
        self.image = image
        self.rect = image.get_rect(center = position)

        self.offset = pygame.math.Vector2(default_offset_claw_x, 0)
        self.position = position

        self.direction = LEFT
        self.angle = 10 #the first angle
        self.angle_speed = 2.5
        

    def update(self):
       # rect_center = self.position + self.offset #mid point
       # self.rect = self.image.get_rect(center = rect_center)
        if self.direction == LEFT: #to the left
            self.angle += self.angle_speed
        elif self.direction == RIGHT:
            self.angle -= self.angle_speed
        

        #when it reaches an edge
        if self.angle > 170:
            self.angle = 170
            self.directon = RIGHT
        elif self.angle < 10:
            self.angle = 10
            self.direction = LEFT   

        print(self.angle, self.direction)  

**Here is my game main variables**

    default_offset_claw_x = 40
    LEFT = -1
    RIGHT = 1 

Here is my main

#claw initialize
claw_image = pygame.image.load(os.path.join(current_path, "img\\claw.png"))
claw = Claw(claw_image, (screen_width//2, 110))
#game loop
running = True

while running:

    clock.tick(30)  # FPS = 30
    # Look at every event in the queue
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    
    screen.blit(background,(0,0))
    
    gemstone_group.draw(screen) #draw all sprites in gemstone_group
    
    claw.update()
    claw.draw(screen)

    pygame.display.update() #display update

pygame.quit()
1 Answers

There is missing an i in directon. It has to be self.direction = RIGHT. Anyway you can simplify the code:

class Claw(pygame.sprite.Sprite):
    # [...]

    def update(self):
        self.angle += self.angle_speed * self.direction
        if self.angle > 170 or self.angle < 10:
            self.anlge = max(10, min(170, self.angle))
            self.direction *= -1
Related