Touches and Moving Sprites in XCode SpriteKit: Swift Crash Course (Free Tutorial)

If you’re designing a game, you probably need your players to move around. In this article, we’ll look at the different ways of doing so in SpriteKit. Want more FREE coding lessons? You’re in luck! We have a free 30-minute beginners course: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

To start a new project, go to File > New > Project. The template we’re using today is the iOS application, which is for the iPhone and iPad. Go to iOS > Application > Game. For Device, specify iPhone. Let’s make our Product Name “Getting started with SpriteKit”. Push Next and then Create. An iPhone app set-up will appear on your screen.

In the left sidebar, open “GameScene.swift”. Delete any excess code until you’re left with this:

import SpriteKit

class GameScene: SKScene {
override func didMoveToView(view: SKView) {

}

override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
/* Called when a touch begins */

for touch in touches {

}
}

override func update(curent Time: CFTimeInterval) {
/*Called before each frame is rendered */
}
}

Let’s create a sprite! On a line below import SpriteKit, declare the variable player, and make it equal to SKSpriteNode. You can use the keyword var and the following format:

var player = SKSpriteNode?()

Next, above the line override func update(currentTime: CFTimeInterval) {, create a new function named spawnPlayer.

func spawnPlayer(){

}

To give our sprite a color and a size, we also need to add the following line within that function:

player = SKSpriteNode(color: UIColor, size: CGSize)

To set the color of the sprite, below var player = SKSpriteNode?(), declare the variable playerColor. We can give it an orange color by typing the following:

var playerColor = UIColor.orangeColor()

Below that, we can also set the background color of our display by declaring the variable backgroundColorCustom and setting it equal to UIColor. For the background to be dark grey, set its Red, Green, and Blue (RGB) values to 0.2 like so:

var backgroundColorCustom = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)

Note that Alpha refers to transparency. Likewise, we can specify that the size of our sprite is, for instance, 50 by 50 pixels by declaring another variable:

var playerSize = CGSize(width: 50, height: 50)

Now, back within the spawnPlayer function, we must replace UIColor with playerColor, and CGSize with playerSize.

Thus our sprite has a color and dimensions. Why don’t we also give it a position? On a new line within the same function, write:

mySprite?.position

As you can see whilst typing “position”, it is a CGPoint. For this reason, we have to set the sprite’s position equal to CGPoint. Furthermore, we can set our sprite’s position inside parentheses after CGPoint. For instance, for our sprite to be positioned in the center of the screen, add onto the existing line so it looks like so:

mySprite?.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY
(self.frame))

If, after y: CGRectGetMidY(self.frame), you add + 200, the sprite will be positioned slightly above the center point of the screen. Remember that X refers to the horizontal axis and Y refers to the vertical axis.

But we’re not done yet! We need one more line in our function:

self.addChild(player!)

Within the override function didMoveToView, we need to reference the background color variable we created:

self.backgroundColor = backgroundColorCustom

Also, we must add a line saying spawnPlayer().

Run the simulator, and you will see an orange square appear on the display. We’ve successfully created a sprite! Next we will add code so that the square on the display moves whenever we drag and pull it with our cursor. To achieve this, first delete the override function touchesBegan.

Instead, we will have a new one called touchesMoved. In the place of the old override function, insert:

override func touchesMoved(touches: Set, withEvent event: UIEvent?) {
for touch in touches{

}
}

Also, within the curly brackets after for touch in touches, type:

let touchLocation = touch.locationInNode(self)

player?.position.x

This will allow us to add in a touch location. As you can see in the tab that pops up when you type it, touch.locationInNode is a CGPoint. This means that we can delete the let before touchLocation = touch.locationInNode(self). This allows us to create a global variable, which we can use throughout the program. We just need to create another variable where we created our other variables, such as on a line beneath var playerSize = CGSize(width: 50, height: 50). Name the new variable touchLocation.

var touchLocation = CGPoint?()

We can now set up our code so that our touch on the screen changes the position of our sprite. In the touchesMoved function, make player?.position.x equal to (touchLocation?.x)!. As well, add the line:

player?.position.y = (touchLocation?.y)!

If you run the simulator, you will be able to move the square around by clicking on it and dragging it. touchesMoved allows you to do this. On the other hand, if you don’t want to drag it and want to have it move to where you touch the display, you can use touchesBegan. Above the touchesMoved function, type override func touchesBegan, and push Enter. XCode will auto-complete the following:

override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
code
}

Now cut the following code from the touchesMoved function:

for touch in touches{
touchLocation = touch.locationInNode(self)

player?.position.x = (touchLocation?.x)!
player?.position.y = (touchLocation?.y)!
}

Replace code in the touchesBegan function with that text. Likewise, you can follow the same steps to create the function touchesEnded. When you click on the display and drag your cursor, the square will move to wherever you let go of the cursor.

 

For our next example, let’s mimic a spaceship shooter game. First off, go back to having only the function touchesMoved. Also, in the spawnPlayer function, change + 200 to - 500.

Let’s say, like in a game of this kind, we want our spaceship to be able to move left and right but not up and down. We can achieve this by simply deleting this line from the touchesMoved function:

player?.position.y = (touchLocation?.y)!

When you make big games, moveThePlayer could have 20 lines of code in it. You don’t always want to put things into your override function. They’re there to set up the functionality. They’re not meant to carry all the programming weight. Instead, since we set touchLocation as a global variable, we can call a new function in order to move our sprite. Below the touchesBegan function, you can create the new function moveThePlayer:

func moveThePlayer(){

}

As well, cut the following line from touchesMoved, and paste it into your new function:

player?.position.x = (touchLocation?.x)!

Run the simulator. You will see the sprite moving left and right when you click and drag your cursor.

There you have it! Not only can you now spawn a new player, you know how to use touchesMoved, touchesBegan, and touchesEnded to make your players move like you want them to. To keep learning how to code for FREE, check out our 30-minute introductory course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

Author Profile

Alexandra Kropova
Alexandra Kropova
Writer of blog posts and books at Mammoth Interactive. Can also be found posting to Mammoth Interactive's social media.

Leave a Reply