Page 1 of 1

how check AABB between 2 classes?

Posted: Thu Apr 26, 2018 6:35 pm
by boruok
Hi can anyone help me please, i'm studyin Love2D framework and getting stucked by checking collision between two classes using rxi/classic - library (Ball and Paddle).
I know how check collision between singe object and objects in table. Like:

function love.update(dt)
for _, v in ipairs(tablename) do
v:update(dt)
-- collision
if AABB(p.x, p.y, p.w, p.h, v.x, v.y, v.w, v.h) then
-- do something
end
end

but dunno how check collision between "two kind of objects in one table" (ball and paddle)

mayble looking my code have better explanation, here my example.
game.love
(12.17 KiB) Downloaded 104 times

Re: how check AABB between 2 classes?

Posted: Fri Jun 29, 2018 3:34 am
by BruceTheGoose
I started by adding an object identifier variable in the constructor of each class.

Code: Select all

function Ball:new(x, y)
       -- ...
        self.type = "ball"

end
Here is how you would check collisions

Code: Select all


checkCollision = 
local function(x1,y1,w1,h1,x2,y2,w2,h2)

    return (x1 + w1 > x2) and (x1 < x2 + w2) and (y1 + h1 > y2) and (y1 < y2 + y2)

end

function love.update(dt)
    for i, v in ipairs(objects) do
        v:update(dt)  
        if(v.type == "paddle") then
          for i = 1,#objects do -- Not good for lots of objects
            if(objects[i].type == "ball") then
              if(checkCollision(v.x,v.y,v.w,v.h,objects[i].x,objects[i].y,objects[i].w,objects[i].h)) then
                objects[i].xv = objects[i].xv * -1 
              end
            end 
          end
        end
    end
end


Here is the working project.

Re: how check AABB between 2 classes?

Posted: Fri Jun 29, 2018 6:16 am
by ivan
You're almost there, a few things that could be improved:

Check every pair of objects only once:

Code: Select all

for i = 1, #objects do
  for j = i + 1, #objects do
    objects[i]:overlaps(objects[j])
  end
end
For classes, try to pass as few parameters as possible:

Code: Select all

function object:overlaps(b)
  local a = self
  if a.x + a.w < b.x or a.x > b.x + b.w then
    return false
  end
  if a.y + a.h < b.y or a.y > b.y + b.h then
    return false
  end
  return true
end

Re: how check AABB between 2 classes?

Posted: Sun Jul 01, 2018 1:22 am
by BruceTheGoose
ivan wrote: Fri Jun 29, 2018 6:16 am You're almost there, a few things that could be improved:

Check every pair of objects only once:

Code: Select all

for i = 1, #objects do
  for j = i + 1, #objects do
    objects[i]:overlaps(objects[j])
  end
end
For classes, try to pass as few parameters as possible:

Code: Select all

function object:overlaps(b)
  local a = self
  if a.x + a.w < b.x or a.x > b.x + b.w then
    return false
  end
  if a.y + a.h < b.y or a.y > b.y + b.h then
    return false
  end
  return true
end
Time to clean up some of my stuff :)
Thank you!