Collision if statement

How do I setup an if statement that activates on collision?

For example:

If my object “hero” collides with “wall”, change a variable.

Thanks.

Do you use physics?

You can assign ids to your objects and than check if the object collided has this or that id.

I messaged you. Thanks!

Hey! Why don’t you try adding names to the objects? My persenal favorite way of doing collisions!

Here’s an example you can put into a main.lua file and it’ll show!

local physics = require("physics") physics.start() physics.setDrawMode( "hybrid" ) local wall = display.newRect( display.contentCenterX - 100, display.contentCenterY, 10, 100 ) physics.addBody( wall, "static" ) wall.myName = "wall" local hero = display.newCircle( display.contentCenterX, display.contentCenterY, 10 ) physics.addBody( hero, "dynamic", { radius = 10 } ) hero.gravityScale = 0 hero.myName = "hero" hero:setLinearVelocity( -100, 0 ) local function onCollision(event) if event.phase == "began" then if event.target.myName == "wall" and event.other.myName == "hero" then local collidedText = display.newText( "Collided!", display.contentCenterX, display.contentCenterY, native.systemFontBold, 20 ) end end end wall:addEventListener( "collision", onCollision )

Good Luck!

Do you use physics?

You can assign ids to your objects and than check if the object collided has this or that id.

I messaged you. Thanks!

Hey! Why don’t you try adding names to the objects? My persenal favorite way of doing collisions!

Here’s an example you can put into a main.lua file and it’ll show!

local physics = require("physics") physics.start() physics.setDrawMode( "hybrid" ) local wall = display.newRect( display.contentCenterX - 100, display.contentCenterY, 10, 100 ) physics.addBody( wall, "static" ) wall.myName = "wall" local hero = display.newCircle( display.contentCenterX, display.contentCenterY, 10 ) physics.addBody( hero, "dynamic", { radius = 10 } ) hero.gravityScale = 0 hero.myName = "hero" hero:setLinearVelocity( -100, 0 ) local function onCollision(event) if event.phase == "began" then if event.target.myName == "wall" and event.other.myName == "hero" then local collidedText = display.newText( "Collided!", display.contentCenterX, display.contentCenterY, native.systemFontBold, 20 ) end end end wall:addEventListener( "collision", onCollision )

Good Luck!