避免碰撞 - 电晕

时间:2014-05-15 13:11:01

标签: lua sprite corona collision

我已初始化名为jet的对象在与其他对象交互时发生碰撞,但是当我移动喷气机并触摸天花板或地板时,它们也会爆炸。如何避免与天花板和天花板碰撞功能地板?这是代码。

天花板对象

ceiling = display.newImage("invisibleTile.png")
ceiling:setReferencePoint(display.BottomLeftReferencePoint)
ceiling.x = 0
ceiling.y = 0
physics.addBody(ceiling, "static", {density=.1, bounce=0.1, friction=.2})
screenGroup:insert(ceiling)
local groundShape = { -280,-20, 280,-20, 280,20, -280,20 }

楼层对象

theFloor = display.newImage("invisibleTile.png")
theFloor:setReferencePoint(display.BottomLeftReferencePoint)
theFloor.x = 0
theFloor.y = 300
physics.addBody(theFloor, "static", {density=.1, bounce=0.1, friction=.2, shape=groundShape })
screenGroup:insert(theFloor)

Jet对象

jetSpriteSheet = sprite.newSpriteSheet("greenman.png", 128, 128)
jetSprites = sprite.newSpriteSet(jetSpriteSheet, 1, 4)
sprite.add(jetSprites, "jets", 1, 15, 500, 0)
jet = sprite.newSprite(jetSprites)
jet.x = 180
jet.y = 280
jet:prepare("jets")
jet:play()
**jet.collided = false**
physics.addBody(jet, {density=0.1, bounce=0.5, friction=1, radius=12})

爆炸性方法

function explode()
explosion.x = jet.x
explosion.y = jet.y
explosion.isVisible = true
explosion:play()
jet.isVisible = false
timer.performWithDelay(3000, gameOver, 1)
end

碰撞方法

function onCollision(event)
if event.phase == "began" then
  if jet.collided == false then 
    jet.collided = true
    jet.bodyType = "static"
    explode()
    storyboard.gotoScene("restart", "fade", 400)
  end
end
end 

究竟需要指定条件以避免胶体对象吗?请帮我解决这个问题

1 个答案:

答案 0 :(得分:3)

注意,如果您不想自己检测所有冲突,则filter collisions. This link.包含一个有用的表和教程,可帮助您确定maskbits和categorybits。另一种选择是组索引,您可以在文档末尾阅读更多on the first link.

但是,从我在你的代码中看到的,你的天花板和地板也可能爆炸。正在发生的是你的碰撞函数onCollision正在对所有对象进行相同处理。您需要为您的喷气机对象jet.name = "jet"指定一个名称,然后在碰撞功能上检查该物体是否真的是喷气机:

function onCollision(event)
    if event.phase == "began" and "jet" == event.object1.name then
        if jet.collided == false then 
            jet.collided = true
            jet.bodyType = "static"
            explode()
            storyboard.gotoScene("restart", "fade", 400)
        end
    end
end 

请注意,您还应该为所有其他物理对象指定一个名称,以防您想对每个身体做一些特别的事情,并且在重新开始游戏后不要忘记重置jet.collided,如果它实现了它。

详细了解碰撞检测on the Corona Docs.