0

Hi I'm new to game dev and I'm using pygame, now I'm in this problem I have multiple enemies that the player has to avoid and kill simultaneously, but my collision detection function checks collision for one enemy at a time. Aside from the first enemy in the list, the function does not work for other enemies from the list. Here's the code for enemy creation and collision detection

class Enemy(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.width, self.height = 30, 30
        self.vel = 10
        self.color = (0, 0, 255)
        self.rect = (x, y, self.width, self.height)

def create_enemies(n):
    enemies = []
    for i in range(n):
        xcor = randint(0, (W - 50))
        ycor = randint(0, H - H/2)
        enemies.append(Enemy(xcor, ycor))
    return enemies

n = 2

enemies = create_enemies(n)

def collision_detection(obj1, obj2list):
    for obj2 in obj2list:
        if (obj2.x < obj1.x < (obj2.x + obj2.width)) and (obj2.y < obj1.y < (obj2.y + obj2.height)):
            return False
        if (obj2.x < obj1.x < (obj2.x + obj2.width)) and (obj2.y < (obj1.y + obj1.height) < (obj2.y + obj2.height)):
            return False
        if (obj2.x < (obj1.x + obj1.width) < (obj2.x + obj2.width)) and (obj2.y < (obj1.y + obj1.height) < (obj2.y + obj2.height)):
            return False
        if (obj2.x < (obj1.x + obj1.width) < (obj2.x + obj2.width)) and (obj2.y < obj1.y < (obj2.y + obj2.height)):
            return False
        if obj1.x == obj2.x and obj1.y <= obj2.y + obj2.height:
            return False
        if obj1.x == obj2.x and obj1.y + obj1.height >= obj2.y:
            return False
        else:
            return True
lol troll
  • 11
  • 5
  • Backticks for code format are `\``, not single quotes which are `'`. – Andras Deak -- Слава Україні Jan 18 '20 at 09:12
  • `PyGame` has `pygame.Rect()` which has methods to check collisions and you don't have to write it - [player.rect.colliderect(enemy.rect)](https://www.pygame.org/docs/ref/rect.html#pygame.Rect.colliderect). It has also `Group` which can be used to check collision will list of enemies. – furas Jan 18 '20 at 09:30

1 Answers1

0

Your problem is in your collision detection logic. Your logic is as follows:

main loop > call collision_detection > iterate over objects

It should be:

main loop > iterate over objects > call collision_detection

This is because if the first object in obj2list collides with obj1, it returns from the function and doesn't check the rest of the objects.

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76