Kalyani Rajalingham
Kalyani Rajalingham

Reputation: 23

Pygame: How to move an image left to right again and again

I'm trying to move an image in pygame from left to right and then back to left, etc...basically, I just want it to go from one end of the screen to the other, and then back to the original position, and keep doing that until it is hit. So I've been trying to write the code and nothing works!

It moves to the right, but then stops. Here's the code I use to move my enemy back and forth. My screen size is width=800, height=600, and so if if my enemy is between 0 and 730 on the x axis, i'm telling it to move right by 0.6. But if my enemy is at a location above 730, i would like it to reverse it's speed, hence the -0.6. And if it's less than 0, then i want it to move right.

# move the enemy
if enemy_x >= 0 and enemy_x <= 730:
    enemy_diff = 0.6
    enemy_x = enemy_x + enemy_diff
if enemy_x > 730:
    enemy_x = 730
    enemy_diff = -0.6
    enemy_x = enemy_x + enemy_diff
if enemy_x < 0:
    enemy_x = 0
    enemy_diff = 0.6
    enemy_x = enemy_x + enemy_diff

What am I doing wrong here?

Upvotes: 2

Views: 775

Answers (1)

Rabbid76
Rabbid76

Reputation: 210909

The problem in your code is enemy_diff = 0.6 under the condition if enemy_x >= 0 and enemy_x <= 730:. The condition is also met if the image is to be moved back.

In initialize the variables before the application loop:

enemy_diff = 0.6
enemy_x = 0

Change enemy_diff if enemy_x is out of bounds in the application loop:

while True:

    # move the enemy
    enemy_x += enemy_diff
    if enemy_x <= 0:
        enemy_x = 0
        enemy_diff = 0.6
    if enemy_x >= 730:
        enemy_x = 730
        enemy_diff = -0.6

Upvotes: 1

Related Questions