0
votes

So I'm trying to remake a flash game I made about a year ago but in love2D. I've got to the point where it's basically finished so I've decided to go and fix a few things.

The first thing was that I was using a normal AABB collision detection on rotated objects and sometimes bullets would go straight through zombies(I fixed this using a tutorial on 2D collision in roblox, go figure.)

The next thing was I wanted zombies to "push away" from eachother when they collided rather than merging into eachother.

The tutorial I used for rotated 2D collision also showed how to move objects away from eachother when they collided.

Each zombie is stored in a table, and then I loop through the tables to do stuff with them (like draw them, update etc. Zombies are created through another class)

But since they're in the same table, I'm not really sure how to go about making sure they're colliding with eachother.

for izom,zom in ipairs(main.zombies) do
    zom:update(dt)
    doesCollide,mtv = collide(zom,zom)
    if collide(zom,zom) then
        zom.Position = zom.Position + Vector2.new(mtv.x, mtv.y);;
    end
end

I tried that, but it doesn't work.

How can I fix this?

1
What's the problem with good ol' nested for? for i=2,#main.zombies do for j=1,i-1 do stuff with zombie[i] and zombie[j] end endDimitry

1 Answers

1
votes

I would go with a nested for loop like Dimitry said.

As far as pushing away goes I would check if the distance between both zombies center points is less than a full width of a zombie, and if so push away.

It would look something like this

    local pushBack=50 --How hard they should push away from eachother

    --Loop through the zombies table twice
    for ia,zombiea in ipairs(main.zombies) do
      for ib,zombieb in ipairs(main.zombies) do

         --Get the distance between the two zombies
         local dx = zombiea.x - zombieb.x
         local dy = zombiea.y - zombieb.y
         distance = math.sqrt ( dx * dx + dy * dy )

         --If the zombies are touching
         if distance<zombiea.width then
            local angle=math.atan2((zombieb.y-zombiea.y),(zombieb.x-zombiea.x))

            --Push zombie A
            zombiea.x=zombiea.x+math.cos(angle)*pushBack*dt
            zombiea.y=zombiea.y+math.sin(angle)*pushBack*dt

            --Push zombie B
            zombiea.x=zombiea.x+math.cos(angle)*pushBack*dt
            zombiea.y=zombiea.y+math.sin(angle)*pushBack*dt

         end
      end
    end

You may need to add a + math.pi to the final distance calculation to get the right directions.

distance = math.sqrt ( dx * dx + dy * dy ) + math.pi

Also you would probably want the pushBack variable to change dynamically depending on how close they are to give it a smoother feel.

Also I don't know how you are handling the movement of the zombies, but hopefully this will still help!