GarySabo GarySabo - 1 year ago 103
Swift Question

How to calculate an SKPhysicsBody on the fly while animating a sprite?

In my original build, my sprites were static, so to make the collision physics as accurate as I could rather than use

passing in the
, I used this tool to define a path SpriteKit's SKPhysicsBody with polygon helper tool.

However now I'm animating the sprites so that they move back and forth during gameplay (obviously my physics path remains static given the above) so my physicsbody no longer matches what the player sees on screen.

The helper tool seemed like a bit of hack that Apple would eventually fix in the API, has there been anything recent in SpriteKit that would help me out here so that I can pass in the
and define a precise physicsbody rather than the hard-coded approach? If not, any other alternatives?

Answer Source

Not sure how performant this would be but you can update the physics body for each animation. has a good snippet for custom animations you can modify it to update the physicsbody.

    let sprite = SKSpriteNode(texture: animFrames[0], normalMap: normals[0])

    let fps = 8.0

    let anim = SKAction.customActionWithDuration(1.0, actionBlock: { node, time in
        let index = Int((fps * Double(time))) % animFrames.count
        (node as! SKSpriteNode).normalTexture = normals[index]
        (node as! SKSpriteNode).texture = animFrames[index]

You’d create the physicsbody for each frame then update the physicsbody in that custom action.

You can use the following to generate a physicsbody for each texture.

    SKPhysicsBody(texture: texture!, size: texture!.size)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download