Noob Collision Detection

Hello, I’m trying to get my head around collision detection so that shots that hit the hero are detected, not when the hero collides with the ground. I’ve been trying to adapt various tutorials without much luck. Here’s my code…

[lua]

local physics = require (“physics”)

physics.start()

physics.setGravity(0,8.5)

– load objects

local hero = display.newRect (160, 350, 15, 30)

hero:setFillColor(140, 140, 140)

physics.addBody (hero, {bounce=0, density=1.0})

hero.myName = “hero”

hero.isDead = false

local bullet = display.newRect (160, 50, 5, 5)

physics.addBody (bullet, {bounce=0, density=1.0})

hero.myName = “bullet”

local floor = display.newRect (0,440,320,40)

physics.addBody (floor, “static”, {bounce=0, density=1.0})

floor:setFillColor(180,150,100)

floor.myName = “floor”

– collision detection

function collision (event)

    if event.object1.myName == “bullet” and event.object2.myName == “hero” then

        print (“hero got shot!”)

        hero.isDead = true

    end

end

hero:addEventListener(“collision”, hero)

[/lua]

Any help would be greatly appreciated :slight_smile:

On a sidenote… where can I find the option to change my forum profile pic? Hunted around everywhere without much luck…

Hi ken46,

just in advance - I’m by far from being expert in collision handling, but I would maybe try this:

  • check for collision between hero and floor, if it “starts” (phase == began") to happen, set a flag for hero object (e.g. hero.onGround = true), when it ends (phase == “ended”) to happen unset it (hero.onGround == false)
  • Then, you can check in collision between hero and bullet, if the flag is on, and act as you want

Btw. I would also recommend using local collision handlers, but that’s just my opinion. Maybe someone could confirm / disapprove this.

Hope I helped a bit.

Hi ken46,

just in advance - I’m by far from being expert in collision handling, but I would maybe try this:

  • check for collision between hero and floor, if it “starts” (phase == began") to happen, set a flag for hero object (e.g. hero.onGround = true), when it ends (phase == “ended”) to happen unset it (hero.onGround == false)
  • Then, you can check in collision between hero and bullet, if the flag is on, and act as you want

Btw. I would also recommend using local collision handlers, but that’s just my opinion. Maybe someone could confirm / disapprove this.

Hope I helped a bit.