简体   繁体   中英

Bit mask not working. SpriteKit Swift

There is a coin and it is only supposed to collide with the player and not push it. Instead the player(finger) gets pushed down and it collides with everything. Here is the code:

var coin=SKSpriteNode(imageNamed: "Coin")
coin.position=CGPoint(x: xPos, y: yPos)
coin.physicsBody=SKPhysicsBody(circleOfRadius: 250)
//coin.physicsBody!.mass=CGFloat(mass);
coin.xScale=1
coin.yScale=1

coin.name="coin";
coin.physicsBody?.contactTestBitMask=1
coin.physicsBody!.collisionBitMask=0
coin.physicsBody!.categoryBitMask=0

self.addChild(coin)

Here is the player's settings:

Finger.physicsBody?.collisionBitMask=0;
Finger.physicsBody?.categoryBitMask=0;
Finger.physicsBody?.contactTestBitMask=1

The problem is that the collisionBitMask of the coin is set to the categoryBitMask of the player. Let me demystify the three collision variables for you:

x.categoryBitMask: This is a way of giving an object "x" a way to identify it.

x.collisionBitMask: Here you will place the categoryBitMask var of the objects you want "x" to be able to COLLIDE with (crash into)

x.contactTestBitMask: Here you will place the categoryBitMask var of the object you want to do something for when they make contact with "x". The contactTestBitMask will call the apple provided function "didBeginContact", and in there you could code what you want to happen when say the coin touches the player.

Some code to help you put the pieces together:

var coinCategory: UInt32 = 1 // categories must be type UInt32
var playerCategory: UInt32 = 2
var nothingCategory: UInt32 = 3 // some other number for not colliding into anything

coin.name="coin";
coin.physicsBody!.categoryBitMask= coinCategory // set category first
coin.physicsBody?.contactTestBitMask = playerContact
coin.physicsBody!.collisionBitMask = nothingCategory // doesn't crash into anything. 
// if you want coins to crash into each other then set their collisionBitMask to the coinCategory  


self.addChild(coin)

and:

Finger.physicsBody?.categoryBitMask= playerCategory;
Finger.physicsBody?.collisionBitMask= nothingCategory;

// This next one only needs to be set on one of the objects when you want the "didBeginContact" function to be called when there is contact
//Finger.physicsBody?.contactTestBitMask = coinCategory

Good Luck!

And it is best practice to not use integer values for the bit masks:

var coinCategory: UInt32 = 0x1 << 1 
var playerCategory: UInt32 = 0x1 << 2
var nothingCategory: UInt32 = 0x1 << 3 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM