2014-05-15 88 views
1

我已經初始化了名爲jet的物體,當它與其他物體相互作用時發生碰撞,但是當我移動噴嘴並碰到天花板或地板時,它們也會發生爆炸。如何避免與天花板碰撞& Floor?這是代碼。避免碰撞 - Corona

天花板對象

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) 

噴氣對象

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 

,如果你想不完全靠自己檢測碰撞到底在哪需要指定,以避免膠體對象的情況?請幫我解決這個問題

回答

3

注意,你應filter collisions.This link.包含一個有用的表和教程,以幫助您確定掩碼位和類別位。另一種替代方法是組索引,您可以在文檔末尾閱讀更多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.