To define a category bit mask enum in Objective-C I used to type:
typedef NS_OPTIONS(NSUInteger, CollisionCategory)
{
CollisionCategoryPlayerSpaceship = 0,
CollisionCategoryEnemySpaceship = 1 << 0,
CollisionCategoryChickenSpaceship = 1 << 1,
};
How can I achieve the same using Swift
? I experimented with enums but can't get it working. Here is what I tried so far.
There is a bit of a bug with UInt, but given I think only 32 bits are used anyway this would work. I would also suggest submitting a radar, you should be able to use any constant value (1 << 2 will always be the same)
Anyway, here's once they've got rid of the bugs with UInts, this would work
enum CollisionCategory: Int{ case PlayerSpaceship = 0, EnemySpaceShip, PlayerMissile, EnemyMissile
Try casting your cases as UInt.
This gets rid of the errors for me.
As noted by, user949350 you can use literal values instead. But what he forgot to point out is that your raw value should be in "squares". Notice how the sample of code of Apple enumerates the categories. They are 1, 2, 4, 8 and 16, instead of the usual 1, 2, 3, 4 , 5 etc.
So in your code it should be something like this:
}
And if you want your player node to collide with either enemy or chicken spaceship, for example, you can do something like this:
I prefer to use like below which works just fine and I think it is the closest way to your original attempt:
P.S.: This is Swift 4
Take a look at the AdvertureBuilding SpriteKit game. They rebuilt it in Swift and you can download the source on the iOS8 dev site.
They are using the following method of creating an enum:
And the setup is like this
And check like this:
An easy way to handle the bitmasks in swift is to create an enum of type UInt32 containing all your different collision types. That is
And then in your Player Class add a physics body and setup the collision detection
And for your Attacker Class (or projectile, bird, meteor, etc.) setup its physics body as
(Note that you can setup the physics body to be whatever shape you want)
Then make sure you have a
SKPhysicsContactDelegate
setup (e.g. you can let your scene be the delegate) and then implement the optional protocol methoddidBeginContact
By adding more ColliderTypes you can detect more collisions in your game.