Best way to "eat" something in SpriteKit

76 views Asked by At

By "eat" I mean: when sprite A (Mario) collides with sprite B (a coin) the collision is detected and the coin is removed from the scene; however, Mario's movement is not altered by the collision with the coin.

At the moment I'm using SKPhysicsContactDelegate to register when Mario and the coin collide, but this seems to require acknowledging the coin as a physical body - which therefore means that Mario's movement is stopped by it.

Should the coin not have a physics body, and instead should I use a different method to see if they contact?

2

There are 2 answers

0
Ron Myschuk On BEST ANSWER

According to Apple...

var categoryBitMask: UInt32 A mask that defines which categories this physics body belongs to.

var collisionBitMask: UInt32 A mask that defines which categories of physics bodies can collide with this physics body.

var contactTestBitMask: UInt32 A mask that defines which categories of bodies cause intersection notifications with this physics body.

So if you just set the contactTestBitMask on "Mario" to the coin categoryBitMask, and set the collisionBitMask on "Mario" to 0 (or not to the coin categoryBitMask) you should get be able to tell when the 2 collide in the didBegin(_ contact: SKPhysicsContact) func but the coin will not impede Mario's movement

0
Steve Ives On

Set up contacts between Mario and the coin without setting up a collision

However, if you wanted the coin to bounce away when Mario hits it, without Mario's movement being affected, you could, in addition to having a contact between Mario and the coin, set up collisions between the coin and Mario BUT NOT between Mario and the coin.

If you do this, when Mario hits the coin, Mario's movement will be unaffected but the coin will bounce off Mario via a physics simulation.

You do this by setting Mario's collisionBitMask to NOT include the coin's categoryBitMask, but have the coins collisionBitMask include Mario's categoryBitMask.

Note that this 'one-way' collision set up does not work for contacts i.e. if Mario is set up to contact the coin with Mario's contactTestBitMask including the coin's category, then it's irrelevant if the coin's contactTestBitMask include's Mario's category or not)