位掩码不起作用。 SpriteKit Swift

时间:2015-02-28 19:43:14

标签: ios swift sprite-kit

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

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

2 个答案:

答案 0 :(得分:3)

问题是硬币的collisionBitMask被设置为播放器的categoryBitMask。让我为你揭开三个碰撞变量的神秘面纱:

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

x.collisionBitMask:在这里,您将放置所需对象的categoryBitMask var" x"能够与(崩溃)合并

x.contactTestBitMask:在这里,当您与" x"进行联系时,您将放置要为其执行操作的对象的categoryBitMask var。 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

祝你好运!

答案 1 :(得分:2)

最佳做法是不对位掩码使用整数值:

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