Search code examples
iossprite-kitskphysicsbodyskphysicsworld

Can't zoom / scale an SKSpriteNode with attached SKPhysicsJoints


I would like to be able to "zoom" in and out in my game, however when I scale the parent "world" SKNode, the joints do not scale accordingly since they have to be added to the SKScene (which is the root node).

Changing the size of the SKScene works, however any HUD graphics I have as children scale along with it.

I have considered creating my HUD as a child of the SKView, but it seems to go against what is recommended by Apple. I also lose the benefit of using SKScene transitions, and end up dealing with numerous ViewControllers instead.

Any suggestions on how to scale an SKSpriteNode and have its joints scale along with it?


Solution

  • The safest way to simulate zoom in/out on a World node is to scale it. However, as you've noticed, scaling the World Node breaks the physics simulation because you're effectively moving and scaling everything in side of the SKScene. So, if you scale the World node to 0.5 to simulate zoom-out, you'll notice that gravity has 2x the effect and things fall much faster.

    The solution is to always set the world scale to 1.0 before the physics simulation is done, and then change it back to what you want to see before it is rendered.

    The way I'm doing it which works without any side effects is to do it in the -didEvaluateActions and -didSimulatePhysics callbacks like so:

    -didEvaluateActions
    {
      [myWorld setScale:1.0];    // must be 1.0 before physics!
    }
    
    -didSimulatePhysics
    {
       [myWorld setScale:worldScale];   // now set correctly for rendering
    }