GarySabo GarySabo - 2 months ago 20
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

rectangleOfSize
for
SKPhysicsBody
passing in the
node
, 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
node
and define a precise physicsbody rather than the hard-coded approach? If not, any other alternatives?

Answer

Not sure how performant this would be but you can update the physics body for each animation. https://github.com/CodeAndWeb/spritekit-dynamic-lighting/blob/master/LightingDemo/LightingDemo/GameScene.swift 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]
    })
    sprite.runAction(SKAction.repeatActionForever(anim));

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)