Nolan Ranolin
Nolan Ranolin

Reputation: 409

How to add label to SCNNode?

I’m trying to add a label to an SCNNode. So far I’ve managed to set a SKLabelNode as the material for the SCNNode. It sort of works, I can the SCNNode becomes the background colour of the SKLabelNode but I can’t see the text. Sometime I can see a red haze (the text colour is red) but no readable text.

I also tried setting the material as a UIView and adding a UiLabel as a sub view. Again it sets as I can the whole SCNNode becomes the background colour of the UiLabel but I can’t see any text.

var block = SCNNode()
var spriteScene = SKScene()
var Lbl = SKLabelNode()

lbl.text = “Hello World”

lbl.color = blue (playground colour literal)
lbl. = 2 //I tried various numbers
lbl.fontColor = SKColor.red
spriteScene.addChild(lbl)

Upvotes: 3

Views: 2652

Answers (1)

Alok Subedi
Alok Subedi

Reputation: 1611

I got it after some hit and trial. I had to try different values before I got these size, scale and rotation to display the label as I want.
note: My node here is SCNPlane with 0.3 width and 0.2 height, so size of SKScene and rectangle and position of label are hard coded accordingly.

func addLabel(text: String){
    let sk = SKScene(size: CGSize(width: 3000, height: 2000))
    sk.backgroundColor = UIColor.clear

    let rectangle = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 3000, height: 2000), cornerRadius: 10)
    rectangle.fillColor = UIColor.black
    rectangle.strokeColor = UIColor.white
    rectangle.lineWidth = 5
    rectangle.alpha = 0.5

    let lbl = SKLabelNode(text: text)
    lbl.fontSize = 160
    lbl.numberOfLines = 0
    lbl.fontColor = UIColor.white
    lbl.fontName = "Helvetica-Bold"
    lbl.position = CGPoint(x:1500,y:1000)
    lbl.preferredMaxLayoutWidth = 2900
    lbl.horizontalAlignmentMode = .center
    lbl.verticalAlignmentMode = .center
    lbl.zRotation = .pi

    sk.addChild(rectangle)
    sk.addChild(lbl)

    let material = SCNMaterial()
    material.isDoubleSided = true
    material.diffuse.contents = sk
    node.geometry?.materials = [material]
    node.geometry?.firstMaterial?.diffuse.contentsTransform = SCNMatrix4MakeScale(Float(1), Float(1), 1)
    node.geometry?.firstMaterial?.diffuse.wrapS = .repeat
    node.geometry?.firstMaterial?.diffuse.wrapS = .repeat
}

Upvotes: 2

Related Questions