Xav
Xav

Reputation: 270

SpriteKit/SKPhysics radialGravityField of same category always attracting each others?

Running into an issue trying to use the radial gravity fields in SpriteKit

I don't want objects of same kind (as define by categoryBitMask to attract each others)

Here's how I do it :

struct PhyscisCategory {
    static let None : UInt32 = 0
    static let All : UInt32 = UInt32.max
    static let Star : UInt32 = 0b1
    static let Planet : UInt32 = 0b10
}
<....>
 Planet1.physicsBody!.categoryBitMask = PhyscisCategory.Planet
 Planet1.physicsBody!.fieldBitMask = PhyscisCategory.Star

 Planet2.physicsBody!.categoryBitMask = PhyscisCategory.Planet
 Planet2.physicsBody!.fieldBitMask = PhyscisCategory.Star

Whatever I tried Planets are always mutually attracted (except if I set the fieldBitMask to 0, but they are of course not anymore attracted by Star either) ! I would expect of this 2 lines of code that only stars gravity fields would behave an effect on planets...

from the documentation :

"fieldBitMask : A mask that defines which categories of physics fields can exert forces on this physics body. When a physics body is inside the region of an SKFieldNode object, that field node’s categoryBitMask property is compared to this physics body’s fieldBitMask property by performing a logical AND operation. If the result is a nonzero value, the field node’s effect is applied to the physics body."

Am I doing anything wrong ?

Upvotes: 0

Views: 623

Answers (1)

Double M
Double M

Reputation: 1503

Your masks are out of whack. In binary, they look like this:

0000 0000 1011 0001 (stars)
0000 1011 0001 0000 (planets)

A logical AND of those two yields a non-zero value :

0000 0000 0001 0000

So if SpriteKit evaluates your planet's field bitmask with another planet's category bitmask, they will attract each other. Try those masks instead:

static let Star : uint32_t = 0x1 << 0
static let Planet : uint32_t = 0x1 << 1

(Not sure if that is valid swift code, but you get the idea). You can extend the masks by always left-shifting one bit further. These masks will then always yield a zero value if being AND-ed.

Upvotes: 1

Related Questions