【发布时间】:2023-03-05 13:09:01
【问题描述】:
问题:一旦玩家节点接触到硬币节点,游戏就会在玩家与边界碰撞时结束。
输出应该是什么:玩家应该能够接触到硬币节点并穿过它,为 scoreLabel 添加一个值。 当前代码:
struct ColliderType {
static let playerCategory: UInt32 = 0x1 << 0
static let boundary: UInt32 = 0x1 << 1
static let coinCategory: UInt32 = 0x1 << 2
static let firstBody: UInt32 = 0x1 << 3
static let secondBody: UInt32 = 0x1 << 4
}
var gameOver = false
var coinInt = 0
coin.physicsBody?.categoryBitMask = ColliderType.coinCategory
coin.physicsBody?.contactTestBitMask = ColliderType.playerCategory
coin.physicsBody?.collisionBitMask = 0
player.physicsBody?.categoryBitMask = ColliderType.playerCategory
player.physicsBody?.contactTestBitMask = ColliderType.boundary | ColliderType.coinCategory
player.physicsBody?.collisionBitMask = ColliderType.boundary
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 == ColliderType.playerCategory && secondBody.categoryBitMask == ColliderType.coinCategory {
self.coin.removeFromParent()
coinInt += 1
coinLabel.text = "\(coinInt)"
}
gameOver = true
self.speed = 0
timer.invalidate()
}
override func touchesBegan(touches: Set<UITouch> , withEvent event: UIEvent?) {
if gameOver == false {
self.player.physicsBody?.velocity = CGVectorMake(1, 3)
self.player.physicsBody?.applyImpulse(CGVectorMake(0, 12))
}
}
更新:
boundary.contactTestBitMask = ColliderType.playerCategory
boundary.categoryBitMask = ColliderType.boundary
boundary.collisionBitMask = ColliderType.playerCategory
coin.physicsBody?.categoryBitMask = ColliderType.coinCategory
coin.physicsBody?.contactTestBitMask = ColliderType.playerCategory
coin.physicsBody?.collisionBitMask = 0
player.physicsBody?.categoryBitMask = ColliderType.playerCategory
player.physicsBody?.contactTestBitMask = ColliderType.coinCategory
player.physicsBody?.collisionBitMask = ColliderType.boundary
func didBeginContact(contact:SKPhysicsContact) {
let firstBody: SKPhysicsBody
let 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 == ColliderType.coinCategory || secondBody.categoryBitMask == ColliderType.coinCategory {
self.coin.removeFromParent()
self.coinInt += 1
self.coinLabel.text = "\(self.coinInt)"
}else if firstBody.categoryBitMask == ColliderType.boundary || secondBody.categoryBitMask == ColliderType.boundary {
gameOver = true
self.speed = 0
timer.invalidate()
}
}
【问题讨论】:
-
关于您的编辑:您的播放器不检查边界,而是相反的方式可能有意义。但是您可能根本不希望 播放器 检查任何联系人以简化事情。
标签: swift sprite-kit collision-detection skspritenode skphysicsbody