I want to move object back and forth in pygame but it only moves left and then it stop

Viewed 322

I am trying to move my boss sprite back and forth but it only moves left and stay there what is the problem with my code.

def horizontal_movement(self):
    self.rect.x-=1
    if self.rect.left<0: #when boss reaches extreme left
        self.rect.x+=1 #move right
        if self.rect.right==screen_width: #when boss reaches extreme right
            self.rect-=1 #move left
            if self.rect.midbottom==[boss_x,boss_y]: #stop the motion when boss reaches original position
                pass
3 Answers
  1. You always move left (-1) as you iterate over this code. No matter what the first move through each iteration is 1 left.
  2. Once you hit the edge of the screen, you move a single position to the right. The code iterates once again and you move back 1 position to the left (as your first line of code as I pointed out above).

This pattern repeats forever: Move left each iteration one space until you hit the edge of the screen and then go back and forth between the edge of the screen and one position to the right over and over and over again.

Instead perhaps that self.rect.x-=1 should be random between (-1 and 1) to move randomly right or left each iteration?

The thing with your code is that it goes left by 1 but then it goes to the right again because if self.rect.right==screen_width: #when boss reaches extreme right evaluates to false You can do something like this:

self.right_movement = False
def horizontal_movement(self):
    if self.right_movement:
        if self.rect.bottom <= boss_x:
            self.right_movement = False
        self.rect.x += 1

    else:
        if self.rect.right >= screen_width:
            self.right_movement = True
        self.rect.x -= 1

Add an attribute the indicates the direction of movement. Change the direction when the enemy reaches the borders:

class YourClassName:
    def __init__(self):
       # [...]
   
       self.direction = -1

    def horizontal_movement(self):
        self.rect.x += self.direction

        if self.rect.left <= 0: #when boss reaches extreme left
            self.direction = 1
        elif self.rect.right <= screen_width: #when boss reaches extreme right
            self.direction = -1
        
        if self.rect.midbottom==[boss_x,boss_y]: #stop the motion when boss reaches original position
            pass
Related