问题在于函数名称" bullet Collision) 碰撞后我无法移除子弹。如果删除行self:removeSelf(),则运行代码。这个错误显示在子弹与敌人发生碰撞之后。
--Physics world creation
local physics = require ("physics")
physics.start()
physics.setGravity(1,1)
--screen
local width=display.contentWidth
local height=display.contentHeight
--game characters
local enemy
local hero
local bullet
local background
local score
local counter
--backGround
background= display.newImage("night_sky.png",width/2,height/2,true)
--collision filters
local heroCollisionFilter = { categoryBits=1, maskBits=2 }
local enemyCollisionFilter = { categoryBits=2, maskBits=7 }
local bulletCollisionFilter = { categoryBits=4, maskBits=2 }
--hero's death
function heroCollision(event)
end
--bullet heat
function bulletCollision(event, self)
print("bullet collided")
if event.other.name == "enemy" then
self:removeSelf()
event.other:removeSelf()
event.other= nil
end
end
--fire
function fireBullet(event)
bullet=display.newImage("bullet.png",hero.x,hero.y )
physics.addBody(bullet,{filter=bulletCollisionFilter})
bullet.name=bullet
local gx = event.x-bullet.x
local gy = event.y-bullet.y
physics.setGravity(gx/10,gy/10)
bullet.collision= bulletCollision
bullet:addEventListener("collision", bulletCollision)
end
function addEnemy()
local enemy = display.newImage("ball.png",40,50)
physics.addBody(enemy,{filter=enemyCollisionFilter})
enemy.gravityScale=0
enemy:addEventListener("tap",fireBullet)
enemy.name= "enemy"
end
addEnemy()
background:addEventListener("tap", fireBullet)
hero = display.newImage("pearl1.png",width/2,height/2,true)
答案 0 :(得分:0)
您没有正确设置碰撞。
bullet.collision
已正确设置为碰撞函数bulletCollision
,但您没有正确设置事件侦听器。您应该bullet:addEventListener("collision", bullet)
而不是bullet:addEventListener("collision", bulletCollision)
。(self, event)
,而不是(event, self)
全部根据the collision documentation。
function bulletCollision(self, event)
print("bullet collided")
if event.other.name == "enemy" then
self:removeSelf()
event.other:removeSelf()
event.other= nil
end
end
function fireBullet(event)
bullet=display.newImage("bullet.png",hero.x,hero.y )
physics.addBody(bullet,{filter=bulletCollisionFilter})
bullet.name=bullet
local gx = event.x-bullet.x
local gy = event.y-bullet.y
physics.setGravity(gx/10,gy/10)
bullet.collision= bulletCollision
bullet:addEventListener("collision", bullet)
end
答案 1 :(得分:0)
每次删除之前,您需要检查显示对象是否为空,如:
if xxx ~= nil then
xxx:removeSelf()
xxx = nil
end