我创造了一个玩家必须收集硬币的游戏。现在出于某种原因,当屏幕上有很多硬币要抓住时,当船与硬币发生碰撞时,它将直接穿过与其碰撞的当前硬币并移除添加到屏幕上的最后一枚硬币。如何才能使碰撞发生的实际硬币从屏幕上移除?
func didBeginContact(contact: SKPhysicsContact) {
var firstBody = SKPhysicsBody()
var secondBody = SKPhysicsBody()
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if (firstBody.categoryBitMask & UInt32(shipCategory)) != 0 && (secondBody.categoryBitMask & UInt32(obstacleCategory)) != 0 {
ship.removeFromParent()
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
let scene = GameOverScene(size: self.size)
self.view?.presentScene(scene, transition: reveal)
}
if (firstBody.categoryBitMask & UInt32(shipCategory)) != 0 && (secondBody.categoryBitMask & UInt32(coinCategory)) != 0 {
coin.removeFromParent()
playerScore = playerScore + 1
playerScoreUpdate()
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
if currentTime - self.lastMissileAdded > 1 {
self.lastMissileAdded = currentTime + 1
self.addMissile()
}
// Current time + 6 takes longer to respawn coins
if currentTime - self.lastCoinAdded > 1 {
self.lastCoinAdded = currentTime + 0
self.addCoin()
}
// Current time + 6 takes longer to respawn coins
//if currentTime - self.lastDiamondAdded > 1 {
// self.lastDiamondAdded = currentTime + 1
//self.addDiamond()
//}
self.moveBackground()
self.moveObstacle()
self.moveCoin()
//self.moveDiamond()
}
答案 0 :(得分:1)
要移除coin
发生碰撞的ship
,请更改didBeginContact
功能中第二个条件内的代码。您必须删除属于secondBody
的节点。在您的代码中,您只需删除coin global variable
。这就是为什么当场景中还有其他硬币时它不起作用的原因。
if (firstBody.categoryBitMask & UInt32(shipCategory)) != 0 && (secondBody.categoryBitMask & UInt32(coinCategory)) != 0 {
secondBody.node?.removeFromParent() // Changed line.
playerScore = playerScore + 1
playerScoreUpdate()
}