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工作得很好!
但是didEnd不知道怎么做呢?
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发布于 2018-02-14 20:04:57
这是因为您使用的是一种名为bitwise AND operator (&). 的方法
按位和运算符(&)组合了两个数字的位。它返回一个新的数字,只有当两个输入数字中的比特等于1时,该数字的位才被设置为1:

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,当您使用按位和运算符时,结果也将是1;当检查结果是否等于零时,结果将为true (它不等于零的任何结果都将返回true)。
let eightBits1: UInt8 = 0b00000001 // 1
let eightBits2: UInt8 = 0b00000001 // 1
let lastBit = eightBits1 & eightBits2 // equals 0b00000001 // 2结果总是与x相同(这等于y),在本例中是1。
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得到的false和不相同的结果将被打印出来,因为按位运算符的结果等于零。
基本上,如果使用两个相同数字的Bitwise AND operator ,则结果总是相同的。
到您的问题:
在你的didBegin里,你在比较:
if (firstBody.categoryBitMask & playerCategoryBitMask) != 0在这里,您的firstBody.categoryBitMask是1,playerCategoryBitMask也是1,因此输入true,然后输入if-语句。
在你的didEnd中,你在比较:
if (firstBody.categoryBitMask & Constants().borderCategoryBitMask) != 0在这里,您的firstBody.categoryBitMask是1,borderCategoryBitMask是4,因此结果是zero,您没有输入if-语句,因为0等于零。
现在您已经知道了这一点,您可以修改代码并使其工作。
https://stackoverflow.com/questions/48712580
复制相似问题