Swift 3 (SpriteKit): Create a texture from a node tree

1.3k views Asked by At

I have been trying to render a node tree into an SKTexture as a possible solution to another question here. I tried searching for an answer to this, and I came across one of Apple's Developer pages (view it here). It says the command which converts a node tree into an SKTexture is this:

func texture(from node: SKNode) -> SKTexture?

Although, the code is incomplete since there is no code which executes the conversion of a node tree to an SKTexture. Am I doing something wrong or what is the complete code that I should use to render a node tree into an SKTexture.

Thanks for any advice, help, and answers!

1

There are 1 answers

7
0x141E On

texture(from:) is an instance method of SKView that takes a node (with zero or more children) as a parameter and returns an optional SKTexture. Since the returned value is an optional, you'll need to unwrap it before using it.

From didMove(to:), you can use the view parameter to create a texture

if let texture = view.texture(from: node) {
    let sprite = SKSpriteNode(texture:texture)
    addChild(sprite)
}

From other methods in the SKScene subclass, use optional chaining

if let texture = self.view?.texture(from: node) {
    let sprite = SKSpriteNode(texture:texture)
    addChild(sprite)
}

You can also render the portion of the node-tree's contents inside of a rectangle with

let rect = CGRect(x:-width/2, y:-height/2, width:width, height:height)
if let texture = self.view?.texture(from: node, crop: rect) {
    let sprite = SKSpriteNode(texture:texture)
    addChild(sprite)
}