How to create image of SKSpriteNode?

Viewed 591

I have a SKSpriteNode with a lot of child nodes. I use that node with all the children very frequently in my game.

A better approach would be to build this node once with all the children, create an image (SKTexture) and use the created texture, as opposed to recreating the SKSpriteNode and all its children.

Is there any way to do this?

2 Answers

SKEffectNode & shouldRasterize

You can us SKEffectNode and set shouldRasterize to true.

let effectNode = SKEffectNode()
effectNode.shouldRasterize = true
scene.addChild(effectNode)

The SKEffectNode's output is rasterized and cached internally. This cache is reused when rendering.

Now just add your sprites to effectNode

effectNode.addChild(sprite0)
effectNode.addChild(sprite1)
effectNode.addChild(sprite2)

The first time the effectNode is rendered, the produced image will be automatically cached. And the cached version will be used for the next frames.

There is actually a very easy way to do this.. I do this all the time to convert ShapeNodes to SpriteNodes (because shapes need 1 draw call per shape, and sprites dont)

let texture = SKView().texture(from: desiredNode)
let newSprite = SKSpriteNode(texture: texture)

or, in your gamescene for brevity:
let newSprite = SKSpriteNode(texture: view!.texture(from: desiredNode))

Related