2016-09-24 53 views
0

我在Swift 3上使用Sprit-kit我的問題是在將子彈射向一個節點(我稱之爲Planet)之後,我不希望節點(Planet)消失我只想要子彈從場景中消失,並且我的節點(Planet)仍然繼續運行,並且如果該節點(Planet)與主玩家發生碰撞,它們都會消失(這裏沒有問題)。我的問題是當子彈與那個節點兩者如何消失在碰撞函數曾經我只是寫Bullet.removefromParent()這裏是我的代碼(我想保持我的星球子彈碰撞,並從現場我的子彈取出後):SpritKit swift 3物理身體碰撞,只刪除一個節點

func CollitionPlannetWithBullet(_ Bullet : SKSpriteNode, Planet : SKSpriteNode){ 
    Bullet.removeFromParent() 
} 

,這是代碼中確實開始了聯繫功能N代表地球和子彈:

if ((firstBody.categoryBitMask == physicsCatagory.Planet) && 
    (secondBody.categoryBitMask == physicsCatagory.Bullet)) || 
    ((firstBody.categoryBitMask == physicsCatagory.Bullet) && 
    (secondBody.categoryBitMask == physicsCatagory.Planet)) { 
     CollitionPlannetWithBullet(firstBody.node as! SKSpriteNode, Planet: secondBody.node as! SKSpriteNode) 
} 
+0

你混淆了自己,在你的if語句,你說body1或body2可以子彈,但在你的'CollitionPlannetWithBullet'(拼寫錯誤?)你是說只有body1是子彈。嘗試並保持一致 – Knight0fDragon

回答

0

我發現這樣做是爲了sublcass SKSpriteNode,然後讓你用,如果讓使用它的子類,一個函數來對待每一個節點在發生碰撞的最佳途徑。

我會推薦閱讀子類化和多態性,因爲它會讓你的代碼更清潔,並給你更多的靈活性來構建你的東西​​。

func evalChainGun_Drone(_ contact: SKPhysicsContact){ 
    let nodeA = contact.bodyA.node 
    let nodeB = contact.bodyB.node 

    //A Items 
    if let shotA = nodeA as? ChaingunBullet { 
     shotA.damage()} 

    if let droneA = nodeA as? Drone { 
     droneA.weaponDamage(droneA.HP_Class, damage: 1, node: droneA, contactLocation: contact.contactPoint) 
    } 

    //B Items 
    if let shotB = nodeB as? ChaingunBullet { 
     shotB.damage()} 

    if let droneB = nodeB as? Drone { 
     droneB.weaponDamage(droneB.HP_Class, damage: 1, node: droneB, contactLocation: contact.contactPoint) 
    } 
} 

我希望這會有幫助。

最好的問候, 亡靈地球

+0

這有何幫助? – Knight0fDragon

+0

plus,請參閱:https://en.wikipedia.org/wiki/Don%27t_repeat_yourself – Knight0fDragon

+0

spritekit的問題在於,您無法真正控制哪個節點是哪個聯繫人,因此您需要處理這兩種情況。雖然我同意重複代碼可能不是最佳實踐,但我不確定有什麼方法可以使用Swift。 –