Georgi B. Nikolov
Georgi B. Nikolov

Reputation: 998

Reusing a single SKView to generate multiple SKTextures for use in SceneKit

I am building a simple 3D SceneKit demo and need to render multiple dynamic texts as textures on planes.

I have my two planes on each of which I want to render different text. This is possible by creating a SceneKit Scene and a SKLabelNode, adding the node to the scene and passing the scene a property of the planes material:

let myLabel = SKLabelNode(fontNamed: "Helvetica")
myLabel.text = "Lorem Ipsum"
myLabel.fontSize = 20
myLabel.fontColor = SKColor.green
myLabel.position = CGPoint(x: 50, y: 50)

skScene = SKScene(size: CGSize(width: 100, height: 100))
skScene?.addChild(myLabel)

let geometry = SCNPlane(width: 5.0, height: 5.0)
let plane = SCNNode(geometry: geometry)
let planeMaterial = SCNMaterial()
planeMaterial.diffuse.contents = skScene

geometry.firstMaterial = planeMaterial

sceneView.scene?.rootNode.addChildNode(plane)

This works for one plane with text, but what if I want to create a new one with a different text? Am I expected to either:

A) Keep creating new SKScenes and SKLabelNodes for each text I need or

B) Somehow reuse the original SKScene, i.e. resize it, draw to it and rasterize it each time a new texture is needed?

I am pretty sure that the correct way would be to reuse it. I know I can rasterize a node to SKTexture by using .texture(), but am not sure how should I implement it in my case.

I tried doing

let texture = self.spriteKitView?.texture(from: winner)
geometry.firstMaterial?.diffuse.contents = texture

And while this builds successfully, I am stuck with a white color instead of the desired text texture ...

Upvotes: 0

Views: 79

Answers (1)

Maetschl
Maetschl

Reputation: 1339

Option a) have a lot of advantages (Not for memory), but you can manipulate objects inside material for creating cool effects. (Like a clock)

If you really want to get SKTexture from reuse Scene after, you can use this syntaxis:

planeMaterial.diffuse.contents = SKView().texture(from: skScene)!

I create this example with 2 solutions for the question, please take a look: https://github.com/Maetschl/SceneKitExamples/tree/master/SKTextureOverPlanes

enter image description here

Upvotes: 1

Related Questions