gpt4 book ai didi

ios - SpriteKit 检测多次碰撞而不是一次(Swift 3)

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:08:27 25 4
gpt4 key购买 nike

我的 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)不会导致问题(例如添加多次得分,删除多个生命,尝试访问已删除的节点或 physicsBody 等)。

有关更多详细信息和可能的解决方案,请参阅此答案:https://stackoverflow.com/a/44384390/1430420

关于ios - SpriteKit 检测多次碰撞而不是一次(Swift 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45750975/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com