That’s my point, I didn’t “already know how to do it”… nobody did, that’s why the docs are there so you can learn how to do it.
(I’ve learned quite a bit over the past 20ish months, however I’m not very good at “teaching” others So hopefully the following will make sense)
Basically when it comes to collisions there are three phases
This is very helpful for deciding when you want something to happen during a collision either with a specific object or any object.
Now, you say “play the audio, ONLY if you touch this “item” or object”
Okay so let’s think about this…
We have two objects - ‘ball’ and ‘rect14’ - and we want something to happen when the ball touches/collides with ‘rect14’.
Now in your own code you give both objects a .myName value, I’m assuming you know why and how it can be used.
Since we’ll want to check for collisions on our ‘ball’ we should add a few things to it -
ball.collision = onballCollision -- this is a reference to what will be the name of our collision function. ball:addEventListener( "collision", ball ) -- this adds a collision listener to the ball object
So we’ve got our objects, each with their own unique identifier and a listener for collisions.
Now we need a collision function.
This is what you have so far -
First thing is to change the name of the function to match the name we created earlier
-- I assume you know what 'self' and 'event' in the parenthesis is for local function onballCollision( self, event ) if ( event.phase == "began" ) then elseif ( event.phase == "ended" ) then audio.play(win) end end
You want this function to apply only when the ‘ball’ collides with ‘rect14’
So think about it… how can we get the name of each object? Well we gave each object their own identifier, so let’s use that!..
Oh, but where do we put it? Well if we want something to happen on the ended phase then it would make sense to add something to that ‘if statement’… but again, how?
Back to the docs!
local function onCollision( event ) if ( event.phase == "began" ) then print( "began: " .. event.object1.myName .. " & " .. event.object2.myName ) elseif ( event.phase == "ended" ) then print( "ended: " .. event.object1.myName .. " & " .. event.object2.myName ) end end
Well this is printing something in the terminal when the event begins and ends…
Back to the docs again (read event.object1 and event.object2 )
Oh so it’s printing the name of the first and second object involved in the collision!.. maybe I can reference what object I want to be the first and second, in addition to whatever event.phase I’m checking for.
(Notice they are using .myName for identifying each object… maybe you could do the same )
Now I don’t want to just type the code you need so you can capo&paste it, no, I gave you some information so you can understand how it works so later on when you want to do more complex collision detection you’ll understand some of the basics of what’s going on.
-Saer