Debug SKPhysicsBody with Swift

Here’s a small extensions that will help you debug SKPhysicsBody Objects using Swift:

extension SKNode {
    func attachDebugRectWithSize(s:CGSize) {
        let bodyPath = CGPathCreateWithRect(CGRectMake(-s.width/2, -s.height/2, s.width, s.height), nil)
        self.attachDebugFrameFromPath(bodyPath)
        CGPathRelease(bodyPath)
    }

    func attachDebugFrameFromPath(path:CGPathRef) {
        var shape = SKShapeNode()
        shape.path = path
        shape.strokeColor = SKColor(red: 1.0, green: 0, blue: 0, alpha: 0.5)
        shape.lineWidth = 2.0
        shape.zPosition = 200
        self.addChild(shape)
    }
}

You can use it like this:

//..
let groundRect = CGRectMake(0, groundTexture.size().height, self.frame.size.width*2, groundTexture.size().height)
var ground = SKNode()
ground.position = groundRect.origin
ground.physicsBody = SKPhysicsBody(rectangleOfSize: groundRect.size)
ground.physicsBody.dynamic = false
ground.attachDebugRectWithSize(groundRect.size)
 

swiftfreak

 

Leave a Reply

Your email address will not be published. Required fields are marked *