我的 SKScene 类中有 3 个 SKSpriteNode。其中一个是玩家,另一个是金色和不可见的完成物体,例如当玩家触摸它时,游戏结束。我的问题是当玩家碰撞金币时,他的金币预算应该只增加 50 金币。但是,Xcode 检测到多次碰撞和黄金预算增加了多次。检测到 50-60 次碰撞而不是一次碰撞。我研究了如何解决这个问题。我发现我应该使用 Bool,我尝试设置 bool 但它没有解决我的问题。有没有人可以帮助我了解如何只检测一次碰撞?这是我的 GameScene 类代码:
import SpriteKit
import GameplayKit
class level3: SKScene, SKPhysicsContactDelegate {
let playerFileName = "player"
let starFileName = "50Gold"
let goalFileName = "goal"
let playerCategory : UInt32 = 0x1 << 1
let goalCategory : UInt32 = 0x1 << 2
let starCategory : UInt32 = 0x1 << 3
override func didMove(to view: SKView) {
super.didMove(to: view)
physicsWorld.contactDelegate = self
let goal = childNode(withName: goalFileName) as! SKSpriteNode
let player = childNode(withName: playerFileName) as! SKSpriteNode
let star = childNode(withName: starFileName) as! SKSpriteNode
player.physicsBody!.categoryBitMask = playerCategory
goal.physicsBody!.categoryBitMask = goalCategory
star.physicsBody?.collisionBitMask = 1
player.physicsBody?.collisionBitMask = 1
goal.physicsBody?.collisionBitMask = 1
goal.physicsBody?.isDynamic = true
goal.physicsBody!.contactTestBitMask = playerCategory
player.physicsBody?.isDynamic = true
star.physicsBody?.isDynamic = true
player.physicsBody?.contactTestBitMask = starCategory
star.physicsBody?.categoryBitMask = starCategory
func didBegin(_ contact: SKPhysicsContact) {
// 1
var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
// 2
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB
} else {
firstBody = contact.bodyB
secondBody = contact.bodyA
}
if firstBody.categoryBitMask == playerCategory && secondBody.categoryBitMask == goalCategory {
contact.bodyB.node?.removeFromParent()
}
if firstBody.categoryBitMask == playerCategory && secondBody.categoryBitMask == starCategory {
PlaySceneViewController.instance.gold += 50
print(PlaySceneViewController.instance.gold)
contact.bodyB.node?.removeFromParent()
}
}
}
}
是的 - 这发生了。处理它的方法(在某些情况下,您不能让 sprite-kit 多次调用 didBegin)是确保您的联系代码适应这一点,并且多次处理契约(Contract)不会导致问题(例如添加多次得分,移除多个生命,尝试访问已移除的节点或物理体等)。
有关更多详细信息和可能的解决方案,请参阅此答案:https://stackoverflow.com/a/44384390/1430420
关于ios - SpriteKit 检测多次碰撞而不是一次(Swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45750975/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |