位掩码不工作。 SpriteKit Swift

Bit mask not working. SpriteKit Swift

有一枚硬币,它只能与玩家碰撞而不是推动它。相反,玩家(手指)被推下并与所有东西发生碰撞。这是代码:

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)

播放器设置如下:

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

问题是硬币的collisionBitMask设置为玩家的categoryBitMask。让我为您揭秘三个碰撞变量:

x.categoryBitMask:这是一种给对象"x"识别它的方法。

x.collisionBitMask:您将在此处放置您希望 "x" 能够与之碰撞(撞入)

的对象的 categoryBitMask 变量

x.contactTestBitMask:在这里,您将放置对象的 categoryBitMask var,当他们与 "x" 联系时,您要为其做些什么。 contactTestBitMask 将调用 apple 提供的函数 "didBeginContact",您可以在其中编写硬币接触玩家时想要发生的代码。

一些代码可以帮助您将各个部分组合在一起:

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)

和:

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

祝你好运!

最好不要对位掩码使用整数值:

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