independent functions in collision detection

hi guys,

I want to create N number of rectangles on the fly to use as sensors. So that each rectangle listens to collisions happening only inside them.

My question is how to add a collision listener that is independent for each rectangle created?

I tried adding Event Listeners to the rectangle, but I can’t seem to get it right as passing the index to the function is not possible.

many thanks. :slight_smile:

[code]
rectangle ={}
rectIndex = #rectangle +1
rectangle[rectIndex]=display.newRect( 0, 0, 10,10 )
physics.addBody( rrectangle[rectIndex], “static”,{ isSensor = true }

rectangle[rectIndex]:addEventListener(“collision”,rectangle[rectIndex]) ----this is wrong

function rectangle[rectIndex]:collision(e){ —this is also wrong
print(“collision”)
}
[/code] [import]uid: 74667 topic_id: 35714 reply_id: 335714[/import]

Hi @potsifera,
I assume you’ve corrected the 2 syntax errors in your code? I’m seeing two of them on line 4 (misspelled “rrectangle” and no ending parentheses on the addBody command).

That aside, you might try something like this:

local function rectCollide( self, event )  
 print("collision")  
end  
  
local rectangles = {}  
rectangles[#rectangles+1] = display.newRect( 0, 0, 10,10 )  
local thisRect = rectangles[#rectangles]  
physics.addBody( thisRect, "static", {isSensor = true} )  
thisRect.collision = rectCollide  
thisRect:addEventListener( "collision", thisRect )  

Please test that out and let me know the result… with several rectangles in a loop, since that’s what your ultimate goal is.

Regards,
Brent [import]uid: 200026 topic_id: 35714 reply_id: 142026[/import]

thanks a lot Brent!, this is what I was looking for :slight_smile: [import]uid: 74667 topic_id: 35714 reply_id: 142092[/import]

Hi @potsifera,
I assume you’ve corrected the 2 syntax errors in your code? I’m seeing two of them on line 4 (misspelled “rrectangle” and no ending parentheses on the addBody command).

That aside, you might try something like this:

local function rectCollide( self, event )  
 print("collision")  
end  
  
local rectangles = {}  
rectangles[#rectangles+1] = display.newRect( 0, 0, 10,10 )  
local thisRect = rectangles[#rectangles]  
physics.addBody( thisRect, "static", {isSensor = true} )  
thisRect.collision = rectCollide  
thisRect:addEventListener( "collision", thisRect )  

Please test that out and let me know the result… with several rectangles in a loop, since that’s what your ultimate goal is.

Regards,
Brent [import]uid: 200026 topic_id: 35714 reply_id: 142026[/import]

thanks a lot Brent!, this is what I was looking for :slight_smile: [import]uid: 74667 topic_id: 35714 reply_id: 142092[/import]