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.
how check AABB between 2 classes?
Forum rules
Before you make a thread asking for help, read this.
Before you make a thread asking for help, read this.
- BruceTheGoose
- Citizen
- Posts: 76
- Joined: Sat Sep 20, 2014 2:54 pm
Re: how check AABB between 2 classes?
I started by adding an object identifier variable in the constructor of each class.
Here is how you would check collisions
Here is the working project.
Code: Select all
function Ball:new(x, y)
-- ...
self.type = "ball"
end
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.
- Attachments
-
- game.love.zip
- (12.7 KiB) Downloaded 98 times
"I don't know."
Re: how check AABB between 2 classes?
You're almost there, a few things that could be improved:
Check every pair of objects only once:
For classes, try to pass as few parameters as possible:
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
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
- BruceTheGoose
- Citizen
- Posts: 76
- Joined: Sat Sep 20, 2014 2:54 pm
Re: how check AABB between 2 classes?
Time to clean up some of my stuffivan 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:For classes, try to pass as few parameters as possible:Code: Select all
for i = 1, #objects do for j = i + 1, #objects do objects[i]:overlaps(objects[j]) end end
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
Thank you!
"I don't know."
Who is online
Users browsing this forum: Ahrefs [Bot], Google [Bot] and 13 guests