SpriteKit Move Sprite along Path iOS Tutorial

With Sprite Kit you can create actions to move sprites along a predifined path. This path can be anything like, for example a line, square or circle. In this tutorial we will move a sprite along some different paths. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and select the Game template.

For product name, use IOSSpriteKitMoveSpritePathTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language, select SpriteKit as Game Technology and make sure only iPhone is selected in Devices.

o to the GameScene.sks file and delete the hello World label. Select the Scene and in the Attributes inspector change the X and Y values of the Anchor point to 0.

Next, we will need an image to use for the sprite movement, we will use the Swift log, so download the image here. Add it to the project. The Game template added some code to the project we will not need. Go to the GameScene.swift file and delete all code inside the GameScene class. Next, add the following didMoveToView method

override func didMove(to view: SKView) {
    // 1
    let logo = SKSpriteNode(imageNamed:"SwiftLogo.png")
    logo.position = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
    // 2
    let path = CGMutablePath()
    path.move(to: CGPoint(x: 0, y: 0))
    path.addLine(to: CGPoint(x: 50, y: 100))
    let followLine = SKAction.follow(path, speed: 3.0)
    // 3
    let reversedLine = followLine.reversed()
    // 4
    let square = UIBezierPath(rect: CGRect(x: 0,y: 0, width: 100, height: 100))
    let followSquare = SKAction.follow(square.cgPath, asOffset: true, orientToPath: false, duration: 5.0)
    // 5
    let circle = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: 100, height: 100), cornerRadius: 100)
    let followCircle = SKAction.follow(circle.cgPath, asOffset: true, orientToPath: false, duration: 5.0)
    // 6
  1. The Swift logo is posititioned on the center of the screen.

  2. A graphic path is created, where a line is added to. The action will move the sprite along the path

  3. The previous action will be reversed, so the sprite will move back to its original position.

  4. Using the UIBezierPath(rect:) method a square path will be created for the SKaction

  5. Using the UIBezierPath(roundedRect:) method a circular path will be created for the SKaction

  6. a runAction with all actions in a sequence will be created, so the actions will run in order.

Build and Run the project and you will see the sprite move along the paths.

You can download the source code of the IOSSpriteKitMoveSpritePathTutorial at the ioscreator repository on Github