Pixeled
Pixeled

Reputation: 322

Why will my obstacles still spawn next to each other when I coded it so they won't?

I am trying to make it so if my two obstacles spawn near each other they will move, but it won't work. Why?

                if obstacle2.rect.x - obstacle1.rect.x > 0:
                    while obstacle1.rect.x - obstacle2 .rect.x < 100:
                        obstacle1.rect.x = (random.randint(300, 900))
                        obstacle2.rect.x = (random.randint(300, 900))
                if obstacle1.rect.x - obstacle2.rect.x > 0:
                    while obstacle2.rect.x - obstacle1 .rect.x < 100:
                        obstacle1.rect.x = (random.randint(300, 900))
                        obstacle2.rect.x = (random.randint(300, 900))

Upvotes: 1

Views: 41

Answers (1)

Iain Shelvington
Iain Shelvington

Reputation: 32294

The while loops are only checking that the objects overlap in a single direction, when you move them they may overlap in the other direction but the while loop condition is satisfied and exits.

Remove your if statements and create a single while loop that checks if they overlap in either direction

while abs(obstacle1.rect.x - obstacle2.rect.x) < 100:
    obstacle1.rect.x = random.randint(300, 900)
    obstacle2.rect.x = random.randint(300, 900)

Upvotes: 2

Related Questions