Search code examples
swiftsprite-kitskphysicsbody

Custom gravity for single node in SpriteKit


I would like to set custom falling speed for selected sprite nodes.

Problem is, if gravity is updated, it will change all of the scene nodes.

If impulse is used, it will have larger speed at the beginning, and the wanted behaviour is gradually speeding up or using constant speed ( this depends on particular node ).

It can be done manually in update function, but maybe there is a better, more elegant, solution?


Solution

  • Use an SKFieldNode with fieldBitMask and categoryBitMask set so that it only affects the desired nodes.

    If you want to have reduced gravity for some nodes, add a linearGravityField to affect those nodes and set its strength to reduce the normal gravity to the degree desired. Or you can set the added field to the desired value directly and have the special nodes' affectedByGravity set to false to turn off the normal gravity for those nodes.

    If you want some falling nodes to reach a constant speed, maybe include a dragField as well and set its strength to balance the gravity acceleration when it reaches the desired terminal velocity.

    https://developer.apple.com/documentation/spritekit/skfieldnode