Adding a collision event / listener.

Hiya,

I’m having an weird time with something here.

I’m trying to add a collision Sensor to an object.
I’ve created my ‘object’ and added physics to it and a ‘isSensor’ to it.

I’ve then created my collision function.
Simply put:

function StarSensor:collision (e)  
 if(e.phase == "began") then  
 audio.play(btnpress);  
 trackStars(self);  
 end  
 return true;   
end  

For some reason this one keeps telling me:

" attempt to index global ‘objSensor’ (a nil value) "
I’ve used other collision sensors in my level but I dunno why this ones not having it.
Get in there!

Is there a limit? (I’m at 3, ‘…:collision’ events so far)
Or are my eyes just missing something stupid?
(I’ve checked and re-checked loads!)

Thanks
PS: And while i’m here, is it okay that my collision functions, like above, don’t have ‘local’ in front of them, everything else does but if i do to those, they return errors. [import]uid: 91798 topic_id: 17253 reply_id: 317253[/import]

I’ve changed it to:

local function StarSensor(e) if(e.phase == "began") then audio.play(btnpress); trackStars(self); end return true; end Star1:addEventListener("collision", StarSensor);

For the time being. And it works.

But still the other way should work too right?

Can you do the previous way involving an image?
(Because the last times i did a :collision they were just newRects)

Just trying to figure it out. [import]uid: 91798 topic_id: 17253 reply_id: 65188[/import]

You can make any image listen for collision provided it is a physics body - not just newRect or newCircle :slight_smile:

For your error - was that the exact output? “objSensor”?

Where do you add star1? Were you trying to add a listener to it before it existed?

Peach :slight_smile: [import]uid: 52491 topic_id: 17253 reply_id: 65216[/import]

Sorry the exact error was ‘StarSensor’
Which correlates to the name i’m trying to give my :collision function.

I add star1 up top when creating the level.

local Star1 = Stars:grabSprite("Star01", true, {Anim = {1, 12, 1200, 0}});  
 Star1:show(\_W/2+56, \_H/2+20, 1, "c");  
 Star1:playClip("Anim");  
 Star1:scale(0.8, 0.8);  
 physics.addBody(Star1, "static", {isSensor = true});  
 Star1:addEventListener("collision", StarSensor); -- even if this is commented out it still errors StarSensor.  

then i :insert the star1.

then i add my StarSensor function further down.

function StarSensor:collision(e) if(e.phase == "began") then audio.play(btnpress); trackStars(self); end return true; end [import]uid: 91798 topic_id: 17253 reply_id: 65250[/import]