Now on collision.
First we must include physics and make it start
local physics = require( "physics" ) physics.start()
Then we need some variables
local hasSoundPlayed = false local mySound = audio.loadSound( "BOINK.wav" )
my sound is BOINK.wav, you must write name of your sound.
Then let’s create 2 objects and floor
local myBall = display.newCircle( 150, 50, 20 ) myBall:setFillColor( 255, 0, 0 ) local myCrate = display.newRect( 50, 150, 50, 50 ) local myFloor = display.newRect( 0, 400, 300, 50 ) myFloor:setFillColor( 0, 255, 0 )
If you run simulator then there wil be 3 objects.
Remember as we talked about properties? For objects created with display.* we can also as for tables add properties so
myCrate.name = "crate" myBall.name = "ball"
Now we must make our objects physical
physics.addBody( myBall, "dynamic", { density = 0.1, friction = 0.9, bounce = 0.5, radius = 20 } ) physics.addBody( myCrate, "dynamic", { density = 100.0, friction = 0.9, bounce = 0.0 } ) physics.addBody( myFloor, "static", { density = 1.0, friction = 0.9, bounce = 0.0 } )
This will make myBall and myCrate react to gravity (“dynamic”) and make myFloor being still in place (“static”).
Now we want to detect collision with myFloor.
Do you remember how I wrote that for each event there is table with different properties and that “collision” had
event.other
? We will use it. event.other is the object with myFloor is colliding. As I also said there is
event.phase
Which will tell us phase of collision. It can be “began” or “ended”. Why event.phase ? Because corona will call our function twice so we must somehow tell what happened - is collision begining or ending.
So if we have event.other as object with which myFloor collided then we can check if it has .name property and is one of our names (“ball”, “crate”).
So taking all into one we have
local physics = require( "physics" ) physics.start() local hasSoundPlayed = false local mySound = audio.loadSound( "BOINK.wav" ) local myBall = display.newCircle( 150, 50, 20 ) myBall:setFillColor( 255, 0, 0 ) local myCrate = display.newRect( 50, 150, 50, 50 ) local myFloor = display.newRect( 0, 400, 300, 50 ) myFloor:setFillColor( 0, 255, 0 ) myCrate.name = "crate" myBall.name = "ball" physics.addBody( myBall, "dynamic", { density = 0.1, friction = 0.9, bounce = 0.5, radius = 20 } ) physics.addBody( myCrate, "dynamic", { density = 100.0, friction = 0.9, bounce = 0.0 } ) physics.addBody( myFloor, "static", { density = 1.0, friction = 0.9, bounce = 0.0 } ) local function onCollisionListener( self, event ) print(event.other.name, event.phase) -- we will exexute it for both phases "began" and "ended" but you can give here other "if" statement to differ them. if event.other.name == "ball" then if hasSoundPlayed == false then audio.play( mySound ) hasSoundPlayed = true end end end myFloor.collision = onCollisionListener myFloor:addEventListener("collision", myFloor)