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 is working great!
However didEnd not sure how to do it?
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 ");
}
}
}
I also have
let playerCategoryBitMask:UInt32 = 1
let borderCategoryBitMask:UInt32 = 4
This is because you´re using a method called the
bitwise AND operator (&)
.Combining the bits only the last bit 1 would return 1 all the rest would return zero.
A simpler explanation:
I declare two variables:
Here both x and y has the value 1, when you use bitwise AND operator the result will be also 1 and when checking if the result it is not equal to zero it would be true (any result that it is not equal to zero would return true).
The result would always be the same as
x
(which is equal toy
) in this case1
.In this case:
You get
false
and not same will be printed out since the result of the bitwise operator it IS equal to zeroBasically, if you use the
Bitwise AND operator
using two identical numbers the result will always be the same number.To your issue:
In your
didBegin
, you´re comparing:Here your
firstBody.categoryBitMask
is 1 andplayerCategoryBitMask
is also 1 hencetrue
and you enter the if-statement.In your
didEnd
you´re comparing:Here your
firstBody.categoryBitMask
is 1 andborderCategoryBitMask
is 4 hence the result iszero
and you don´t enter the if-statement because 0 it is equal to zero.Now that you know this, you can modify your code and make it work.