I’m making a simple space shooter game that, so far, consists of three types of objects: the player ship, enemy ships and projectiles. I created the player ship and the enemy ships the same way, singularly, but with the projectiles I had to work around a bit so they could be dynamically created each time tapped the screen…I think that is the problem because collisions are working properly between the player ship and the enemy ship but not between the projectiles and anything else (yes, it’s actually possible for the player ship to shoot itself…I’ll fix that eventually…it’s just a matter of the ship going faster than the projectiles). I’ll post the pertinent code:
projectiles = display.newGroup() projectiles.anchorChildren = true projectiles.anchorX = 0 projectiles.anchorY = 0 projectiles.x = 0 projectiles.y = 0 projectiles.name = 'projectiles' physics.addBody(projectiles, "static", {density = 1, bounce = 0.1, friction = .2, radius = 5}) projectiles.isBullet = true projectiles.isSensor = true screenGroup:insert(projectiles) function shoot() shot = display.newImageRect('shot.png', 17, 6) shot.anchorX = .5 shot.anchory = .5 shot.x = ship.x + 75 \* -math.sin(math.rad(-90 + ship.rotation)) shot.y = ship.y + 75 \* math.cos(math.rad(-90 + ship.rotation)) shot.angle = ship.rotation shot.name = 'projectiles' physics.addBody(shot, "static", {density = 1, bounce = 0.1, friction = .2, radius = 5}) shot.isBullet = true shot.isSensor = true transition.to(shot, {rotation = ship.rotation, time = 0}) projectiles:insert(shot) end local function onLocalCollision(self, event) if ( event.phase == "began" ) then print( self.name .. ": collision began with " .. event.other.name ) elseif ( event.phase == "ended" ) then print( self.name .. ": collision ended with " .. event.other.name ) end end
I’m pretty new to lua and, though it seems simple enough, I’m sure there are nuances I’m missing; I’m not a very good programmer anyway and, truthfully, this part of the code I didn’t even come up with. As you can see, I’m creating a projectiles object, which will later hold all of the shot objects, which are the actual projectiles. Right now the only thing I want the collision to do is acknowledge a collision has happened and, as I said, it works with all of the objects except for the projectiles. Originally only the shot objects had physics but when the collision didn’t work I added the projectiles object to the physics as well but that didn’t help any…then I added isBullet and isSensor to both objects and that didn’t work. I’m at a loss now, I’m sure it’s something stupidly simple…I just can’t see it so I figured I’d post this for you guys to solve while I work on other things. If it helps I can post the rest of the code.