我创建了3个气球(只需要3个),每个气球都包含一个特定的单词,其中一个单词是正确的答案。我从大炮中射出一颗球,击中了气球。假设气球3持有气球文本3,这是正确的答案,如果我击中它的球和文本消失。由于某种原因,ballCollision(事件)没有运行,我使用print语句来确认它。怎么了?
local cannonBalls = display.newGroup()
...
local shot = function(event)
if(event.phase == 'ended') then
Runtime:removeEventListener('enterFrame', charge)
cannon.isVisible = true
cannon.rotation = 0
cannonBall = display.newImage('cannon ball.png', 84, 220)
physics.addBody(cannonBall, {density = 1, friction = 0, bounce = 0})
cannonBalls:insert(cannonBall)
print ('shot')
-- Shoot cannon ball
cannonBall:applyLinearImpulse(3, impulse, cannonBall.x, cannonBall.y )
--Collision listener
print('event listener')
cannonBall:addEventListener ('collision', ballCollision)
end
end
function ballCollision(event)
if (event.other.name =='balloon3') then
scene.updateScore()
print('Ball is colliding')
timer.performWithDelay(1, e.target.removeSelf, e.target)
timer.performWithDelay(1, e.other.removeSelf, e.target)
balloonText3.isVisible = false
audio.play(pop)
end
end
function scene:createScene(event)
local group = self.view
...
local balloon1 = display.newImage ('balloon_fat_red.png', 495, 60)
local balloon2 = display.newImage ('balloon_fat_red.png', 495, 115)
local balloon3 = display.newImage ('balloon_fat_red.png', 495, 160)
group:insert(balloon1)
group:insert(balloon2)
group:insert(balloon3)
physics.addBody(balloon1)
physics.addBody(balloon2)
physics.addBody(balloon3)
balloon1.bodyType = 'static'
balloon2.bodyType = 'static'
balloon3.bodyType = 'static'
table.insert(balloons, balloon1)
table.insert(balloons, balloon2)
table.insert(balloons, balloon3)
local balloonText1 = display.newText('227129130', 495, 60)
balloonText1:setFillColor( 1,1, 0 )
local balloonText2 = display.newText('227129132', 495, 115)
balloonText2:setFillColor( 1,1, 0 )
local balloonText3 = display.newText('227129134', 495, 160)
balloonText3:setFillColor( 1,1, 0 )
group:insert(balloonText1)
group:insert(balloonText2)
group:insert(balloonText3)
end
我假设您将打印语句放在ballCollision
的if
块中,因为我看不出侦听器注册有任何其他错误。另外,我在代码中没有看到任何地方设置了气球对象的name属性。所以要么
- 设置
bodyType
后添加balloon3.name = "balloon3"
(1和2类似),
或(可能更简单)
- 在碰撞处理程序中使用
if event.other == balloons[3] then ...
。在Lua中,不需要在条件周围加上括号。