Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

sprite kit - SKPhysicsBody avoid collision Swift/SpriteKit

I have 3 SKSpriteNodes in my Scene. One bird, one coin and a border around the scene. I don't want the coin and the bird to collide with each other but withe the border. I assign a different collisionBitMask and categoryBitMask to every node:

enum CollisionType:UInt32{
    case Bird  = 1
    case Coin = 2
    case Border = 3 
}

Like so:

bird.physicsBody!.categoryBitMask = CollisionType.Bird.rawValue
bird.physicsBody!.collisionBitMask = CollisionType.Border.rawValue

coin.physicsBody!.categoryBitMask = CollisionType.Coin.rawValue
coin.physicsBody!.collisionBitMask = CollisionType.Border.rawValue

But the coin and the bird still collide with each other. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The bitmask is on 32 bits. Declaring them like you did corresponds to :

enum CollisionType:UInt32{
    case Bird = 1 // 00000000000000000000000000000001
    case Coin = 2 // 00000000000000000000000000000010
    case Border = 3 // 00000000000000000000000000000011
}

What you want to do is to set your border value to 4. In order to have the following bitmask instead :

enum CollisionType:UInt32{
    case Bird = 1 // 00000000000000000000000000000001
    case Coin = 2 // 00000000000000000000000000000010
    case Border = 4 // 00000000000000000000000000000100
}

Keep in mind that you'll have to follow the same for next bitmask : 8, 16, ... an so on.

Edit :

Also, you might want to use a struct instead of an enum and use another syntax to get it easier (it's not mandatory, just a matter of preference) :

struct PhysicsCategory {
    static let None       : UInt32 = 0
    static let All        : UInt32 = UInt32.max
    static let Bird       : UInt32 = 0b1       // 1
    static let Coin       : UInt32 = 0b10      // 2
    static let Border     : UInt32 = 0b100     // 4
}

That you could use like this :

bird.physicsBody!.categoryBitMask = PhysicsCategory.Bird
bird.physicsBody!.collisionBitMask = PhysicsCategory.Border

coin.physicsBody!.categoryBitMask = PhysicsCategory.Coin
coin.physicsBody!.collisionBitMask = PhysicsCategory.Border

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...