Problems with collision detection

I’m probably missing something fundamental, but this is driving me crazy…

I have two sprites and I want to run a collision detection and trigger an event when they collide (obviously). I assume I need to use the collision detection from the physics engine to do this so I’ve written the code below, but it never seems to detect the intersection of the objects (basically the code sticks a static ship on one side of the screen and the other advances towards it and then hits it).

Can someone please tell me what I’m doing that’s fundamentally wrong?

[code]
display.setStatusBar(display.HiddenStatusBar)
local physics = require(“physics”)
physics.start()

local function onLocalCollision( self, event )
if ( event.phase == “began” ) then

print( self.myName … ": collision began with " … event.other.myName )

elseif ( event.phase == “ended” ) then

print( self.myName … ": collision ended with " … event.other.myName )

end
end

– Create the user ship
local userShip = display.newImage(“userShip.png”)
userShip.x = 45; userShip.y = display.contentHeight / 2
userShip.name = “playerShip”
physics.addBody(userShip, “kinematic”)
userShip.collision = onLocalCollision
userShip:addEventListener(“collision”, userShip)

– Add extra ship for collision testing
local testShip = display.newImage(“userShip.png”)
testShip.x = display.contentWidth; testShip.y = display.contentHeight / 2
testShip.name = “testShip”
physics.addBody(testShip, “kinematic”)
testShip.collision = onLocalCollision
testShip:addEventListener(“collision”, testShip)
transition.to(testShip, {time=5000, x=-40})

[/code] [import]uid: 45444 topic_id: 8622 reply_id: 308622[/import]

Replace “name” in lines 22 and 31 with “myName”.

So rather than;
[lua]userShip.name = “playerShip”[/lua]
You’d have;
[lua]userShip.myName = “playerShip”[/lua]

Peach :slight_smile: [import]uid: 10144 topic_id: 8622 reply_id: 30964[/import]

one of the ships has to be “dynamic” for the collision to work , so you’ll have to set gravity to 0 to stop it dropping. [import]uid: 8366 topic_id: 8622 reply_id: 30985[/import]

Thanks guys, I would never have cracked this on my own… [import]uid: 45444 topic_id: 8622 reply_id: 31087[/import]

I was the same way with collision detection at first; trust me, after a little while it will become second nature to you :slight_smile:

Good luck with your game! [import]uid: 10144 topic_id: 8622 reply_id: 31091[/import]