Discord
Login
Community
DARK THEME

Collision with enemies

I create multiple enemiesby doing:

createEnemies = function()
  enemy = object
    //enemy's stuff
  end
  enemies.push(enemy)
end

I also want them to move but they go through each other...

How can i avoid it?

first you need to know how to check for collisions. You could use something like this:

check_collision = function(x1, y1, x2, y2)
if x1 > x2 + tile_size - 1 then return false end
if x1 + tile_size - 1 < x2 then return false end
if y1 > y2 + tile_size - 1 then return false end
if y1 + tile_size - 1 < y2 then return false end
return true
end

So you want to check if the new location doesn't overlap with all the other enemies (with a for-loop). If you don't have a crazy amount of enemies, this works just fine.

Thanks!

But i don't understand how i should use the function

i try

for e1 in enemies
    for e2 in enemies
      if e1 != e2 then
        if not checkCollision(e1.x, e1.y, e2.x, e2.y) then
          //enemy move
        end
      end
    end
  end

But it don't work. What am i doing wrong?

See how I did it. This method is called AABB collision detection .

https://microstudio.dev/i/Loginus/collision/

Thanks everyone but i almost found a way

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community