Developing in iOS 7 Sprite Kit with physics bodies is fun and easy. But there are no debugging options for the physics engine. Sooner or later you will reach the point where you need to see the physics bodies you created to analyse their behaviour.
I’ve written a tool named “PhysicsDebugger” for this case. It displays all the physics bodies in your Sprite Kit Scene. The PhysicsDebugger will draw the real physicsBody, not just the shape dimensions, like other examples on the web will do. To see how the PhysicsDebugger displays its shapes, take a look to the following demo scene. It illustrates some sprites with a drawn physicsBody that differs from the node’s shape or graphic:
The PhysicsDebugger can be easily included with CocoaPods into existing projects. Just add the line:
pod 'PhysicsDebugger' to your existing Podfile in your workspace.
For those who don’t use CocoaPods, a complete Xcode demo project can be downloaded on gitHub. Feel free to fork and contribute to this repository. Copy the files from the PhysicsDebugger/YMCPhysicsDebugger/* folder into your Sprite Kit project manually
Import the header files to your Sprite Kit game file:
Before your SKNodes are created, init the PhysicsDebugger with the following line:
After your SKNodes are created call the PhysicsDeugger render method:
Not all types of physicsBody are supported yet. PhysicsBody shapes will be attached to the following PhysicsBody method calls:
Sprite Kit Nodes that will be added after the method call
[self drawPhysicsBodies]; will not be drawn yet.
How it works
When calling the PhysicsDebugger initialisation, a so called method “swizzling” will be enabled. Swizzling means any method call can be routed to another method call. Swizzling is kind of evil and should only be used if you know exactly what you are doing… they say. It’s used in this way because the Sprite Kit physicsBody object itself has no accessible properties. So you can’t just take the physicsBody object, read for example it’s radius and draw a shape with that.
In this case, the swizzling method is simply used to route the generating calls for a physicsBody object like bodyWithCircleOfRadius. The method that bodyWithCircleOfRadius is routed to will return the physicsBody so nothing “evil” happens. But additionally in this swizzled method, the argument of the physicsBody object, for example the radius or the size, will be stored in a singelton class property.
So just the inital argument of the physicsBody object will be saved to use it afterwards for drawing a shape node.
The category method drawPhysicsBodies will iterate all children of the passed object. In every step the previously saved attributes will be used to draw a shape and attach it to each child node.
See this illustration for details:
The complete Xcode demo project can be downloaded on gitHub. Feel free to fork and contribute to this repository. I’m looking forward to your comments or requests for new articles.