SKPhysicsBody避免碰撞Swift/SpriteKit [英] SKPhysicsBody avoid collision Swift/SpriteKit

查看:136
本文介绍了SKPhysicsBody避免碰撞Swift/SpriteKit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的场景中有3个SKSpriteNodes.场景中有一只,一只硬币边界.我不希望硬币彼此碰撞,但与边界碰撞. 我为每个节点分配了一个不同的collisionBitMask和categoryBitMask:

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 
}

像这样:

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?

推荐答案

位掩码为32位.像您一样声明它们对应于:

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
}

您要做的是将边界值设置为4.为了具有以下位掩码,请执行以下操作:

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
}

请记住,下一个位掩码必须遵循相同的设置:8,16,...依此类推.

此外,您可能希望使用结构而不是枚举,并使用另一种语法来简化操作(这不是强制性的,只是出于喜好考虑):

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
}

您可以这样使用:

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

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

这篇关于SKPhysicsBody避免碰撞Swift/SpriteKit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆