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

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

问题描述

我的场景中有 3 个 SKSpriteNode.一个,一个硬币和一个边框在场景周围.我不希望 coinbird 相互碰撞,但要在 border 内.我为每个节点分配了不同的 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天全站免登陆