func didBegin(_ 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 & Constants().playerCategoryBitMask != 0) { if(secondBody.categoryBitMask & Constants().borderCategoryBitMask == 4) { touchingWall = true print("Touching the wall "); } } }
didBegin工作得很好!
但是不知道怎么办呢?
func didEnd(_ 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 & Constants().borderCategoryBitMask != 0 ) { if(secondBody.categoryBitMask & Constants().playerCategoryBitMask != 0 ) { touchingWall = false print("Not Touching the wall "); } } }
我也有
let playerCategoryBitMask:UInt32 = 1 let borderCategoryBitMask:UInt32 = 4
这是因为您使用的是名为
原文链接:https://www.f2er.com/swift/318592.htmlbitwise AND operator (&)
的方法.
The bitwise AND operator (&) combines the bits of two numbers. It
returns a new number whose bits are set to 1 only if the bits were
equal to 1 in both input numbers:
let eightBits1: UInt8 = 0b00000001 let eightBits2: UInt8 = 0b00000001 let lastBit = eightBits1 & eightBits2 // equals 0b00000001
将这些位组合起来只有最后一位1将返回1所有其余位将返回零.
一个更简单的解释:
我声明了两个变量:
let x = 1 let y = 1
这里x和y的值都是1,当你使用按位AND运算符时,结果也是1,当检查结果是否不等于零时,它将为真(任何不等于零的结果都会返回真正).
let eightBits1: UInt8 = 0b00000001 // 1 let eightBits2: UInt8 = 0b00000001 // 1 let lastBit = eightBits1 & eightBits2 // equals 0b00000001 // 2
在这种情况下,结果总是与x(等于y)相同.
if (x & y) != 0 { print("Same") } else { print("Not same") }
在这种情况下:
let x = 1 let y = 2 let eightBits1: UInt8 = 0b00000001 // 1 let eightBits2: UInt8 = 0b00000010 // 2 let noBits = eightBits1 & eightBits2 // equals 0 -> 0b00000000
由于按位运算符的结果它等于零,因此将打印出错并且不会打印出来
基本上,如果使用按位AND运算符使用两个相同的数字,结果将始终是相同的数字.
对你的问题:
在你的didBegin中,你要比较:
if (firstBody.categoryBitMask & playerCategoryBitMask) != 0
这里你的firstBody.categoryBitMask是1而playerCategoryBitMask也是1,因此你输入if语句.
在你的didEnd你比较:
if (firstBody.categoryBitMask & Constants().borderCategoryBitMask) != 0
这里你的firstBody.categoryBitMask是1,borderCategoryBitMask是4,因此结果为零,你不输入if语句,因为0它等于零.