Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Wrap Text Around a Circle in Sprite Kit / Swift

I am making a game with SpriteKit / Swift and I want to have an effect on the menu scene where I bend a string around a circle. The following picture is almost exactly what I am looking to accomplish. http://www.heathrowe.com/tuts/typeonaapathimages/4.gif

like image 929
Sam Acquaviva Avatar asked Dec 19 '22 00:12

Sam Acquaviva


1 Answers

The following code wraps the characters in a string around the top half of a circle by creating a label node for each character in the string, setting the position of the label to the appropriate location on the circle, and then rotating each label node so that it is tangent to the circle at that position.

class GameScene:SKScene {
    override func didMove(to view:SKView) {
        let radius = CGFloat(50.0)
        let circleCenter = CGPoint.zero

        let string = "Your Text Here"
        let count = string.lengthOfBytes(using: String.Encoding.utf8)
        let angleIncr = CGFloat.pi/(CGFloat(count)-1)
        var angle = CGFloat.pi
        // Loop over the characters in the string
        for (_, character) in string.characters.enumerated() {
            // Calculate the position of each character
            let x = cos(angle) * radius + circleCenter.x
            let y = sin(angle) * radius + circleCenter.y
            let label = SKLabelNode(fontNamed: "Arial")
            label.text = "\(character)"
            label.position = CGPoint(x: x, y: y)
            // Determine how much to rotate each character
            label.zRotation = angle - CGFloat.pi / 2
            label.fontSize = 30
            addChild(label)
            angle -= angleIncr
        }
    }
}

enter image description here

like image 110
0x141E Avatar answered Dec 27 '22 12:12

0x141E