0

In SpriteKit I wish to assign the contactTestBitMask value to a set of values.

This is the normal way:

sprite.physicsBody?.contactTestBitMask = ColliderType.goal.rawValue | ColliderType.greyBox.rawValue

meaning my sprite notifies me when it comes it contact with these collider types. However my problem is that my collider types will be dynamically changing during gameplay and the sprite contactTestBitMask also needs to be changed. I was thinking of using a set collider types and assigning different sets and appropriated times:

sprite.physicsBody?.contactTestBitMask = SetManager.sharedSetManager.normalSet 

In SetManager Class:

    enum NormalColliderType:UInt32 {
    case greyBox = 0
    case enemy = 2
    case goal = 4
    case coin = 8
    }

var currentSet: Set<Int> = []

var normalSet: Set<UInt32> = [NormalColliderType.greyBox.rawValue | NormalColliderType.goal.rawValue]

static let sharedSetManager = SetManager()

Theoretically, its doable but the only error I'm receiving is: "Cannot assign value of type 'Set' to type 'UInt32'" I guess I'm asking how a set can be used as a variable

jtmwanakhu
  • 623
  • 1
  • 6
  • 17
  • You can add a `greyBoxAndGoal` case to your `enum` with value of 5 (`greyBox` should be 1 not 0). – 0x141E Jan 27 '16 at 05:39

2 Answers2

2

contactTestBitMask is of type UInt32, so the type of normalSet can be just UInt32, and you can store it as so.

var normalSet: UInt32 = NormalColliderType.greyBox.rawValue | NormalColliderType.goal.rawValue
Dominic K
  • 6,975
  • 11
  • 53
  • 62
  • To add to this, I would create a dictionary of UInt32 so that you are not creating a ton of variables. let collisionTypes = [UInt](); collisionTypes["normalSet"] = NormalColliderType.greyBox.rawValue | NormalColliderType.goal.rawValue; – Knight0fDragon Apr 11 '16 at 16:16
1

Don't forget that you can set and clear individual collision and contact bits for specific categories using the bitwise AND and NOT operators, without affecting any other bits:

Turn off a specific contact (or collision) :

sprite.physicsBody?.contactTestBitMask &= ~ColliderType.goal.rawValue

sprite contacts with the goal will no longer be notfied.

turn on a specific contact/colission:

   sprite.physicsBody?.collisionBitMask |= ColliderType.newItem.rawValue

sprite will now collide with the newItem

Steve Ives
  • 7,894
  • 3
  • 24
  • 55
  • For simple changes I would take this approach (only changing 1 category at a time), but for multiple category swapping, I would predefine the sets like the other answer to avoid any chance of error when swapping the categories. – Knight0fDragon Apr 11 '16 at 16:17