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

Changing Background Color in XCode SpriteKit: Swift Crash Course (Free Tutorial)

Designing an application? One of the first things you need to think about is a color scheme, which includes the background color of your app. Today we’re looking at how to set the color of the display (background color) of an iPhone or iPad app. Want more FREE coding lessons? 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. Select 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 extra code until your screen looks like 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 */
}
}

On a line underneath import SpriteKit, declare a variable using the keyword var. I like to call this variable backgroundColorCustom because backgroundColor too closely resembles a reserved word. Swift needs reserved words, such as class, SKScene, and override, in order to run code.

var backgroundColorCustom

To give our background a custom color, add onto that line until it looks like this:

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

We are now able to set the Red, Green, and Blue (RGB) values for our color, as well as the alpha (transparency). Let’s say we want a dark gray. Replace the CGFloat after red, green, and blue with 0.2. Likewise, give alpha a value of 1.0.

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

If you prefer to use one of Swift’s default colors, such as orange, you can make your variable equal to UIColor.orangeColor(). Regardless, within the override function didMoveToView, we must reference our new variable:

self.backgroundColor = backgroundColorCustom

Run the simulator to see an iPhone display with a dark gray background. If you zoom in, you will notice that the bottom right-hand corner of the display gives you some values: nodes and fps. What are they?

Let’s find out. Exit out of the display, and open a sidebar listing your SpriteKit files. Then open GameViewController.swift, which controls which scene gets shown on an application. Therefore, if you want to change the scene, you need to edit this file.

As you may be able to tell, the reason our display showed the node count and frames per second (FPS) is because there are the following lines in the GameViewController.swift file:

skView.showsFPS = true
skView.showsNodeCount = true

To not show these values, simply add // in front of each of the lines to turn them into comments, which aren’t read by the compiler.

That is how to set the background color in XCode SpriteKit with Swift. 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

Introduction to UIColor in XCode SpriteKit: Swift Crash Course (Free Tutorial)

Trying to figure out how to make your iOS game stand out? Colors are a key part of game design and can make or break the difference between a game’s success and flop. In this tutorial, we’re going to experiment with colors in SpriteKit and how they can be used to make your application unique. 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. Firstly, it’s a good idea to run the simulator in order to test that the project loads correctly.

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 begin placing a sprite! A sprite is a 2D bitmap graphic that’s part of a larger scene. On a new line above override func update(currentTime: CFTimeInterval) {, add in a function using the keyword func. Name the function spawnSprite.

func spawnSprite(){

}

In order to spawn a sprite, you also need to add in a variable using the keyword var. On a line below import SpriteKit, create the variable player, and set it equal to SKSpriteNode:

var player = SKSpriteNode?()

Add spawnSprite() on a line below override func didMoveToView(view: SKView) {. This will call the spawnSprite function, which will then create a sprite.

In addition, within the spawnSrite function, write this line:

player = SKSpriteNode

At the end of the line, in parentheses, you can add different items. For this example, let’s specify the color and size of our sprite. Insert the following into parentheses: color: UIColor, size: CGSize.

We’ll set the User Interface (UI) Color first. Below var player = SKSpriteNode?(), create the new variable var playerColor, and make it equal to UIColor. At the end of that line, insert: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat).

Editing the Red, Green, and Blue (RGB) values allows us to manipulate the color. Replace the CGFloat after red with 1. As well, replace the CGFloat after green and blue with 0.5. Alpha refers to the transparency. Give alpha the value 1.0.

We can also decide the size of our sprite by declaring a new variable. Let’s call it playerSize. Make the variable equal to CGSize. In parentheses, you can set the width and height to values such as 50:

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

Then, in the spawnSprite function, replace UIColor with playerColor. Likewise, replace CGSize with playerSize. You may be thinking: why create new variables rather than setting the specifications in the function itself? Well, if you need to tweak your values later, they will be easier to find.

As such, our sprite has a color and dimensions. How about a position? On a new line within the same function, write:

mySprite?.position

As you can see whilst typing “position”, it is a CGPoint. Thus we have to set our sprite 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))

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

self.addChild(player!)

Run the simulator, and you will see a salmon square appear on the display.

We can manipulate the colors even more! Change the Green and Blue values of playerColor from 0.5 to 0.0. Additionally, change the Red value to 0.85. If we left the value at 1, we would get a standard red color. By making the value not quite 1, our color and therefore game are more unique.

Let’s also edit the background color. Declare a new variable backgroundColorCustom, and make it equal to UIColor. Set the RGB values to 0.2. Set the alpha value to 1.0. Note that these values are CGFloats.

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

Then, in the override function didMoveToView, write a new line:

self.backgroundColor = backgroundColorCustom

To manipulate our color further, we can add a blue. Declare another variable colorBlue. Use this format:

var colorBlue : CGFloat = 0.0

Also have:

var floatColorAdd : CGFloat = 0.0

Next, we can have the color of our sprite alter slightly whenever the display is touched. To achieve this, type the next line underneath for touch in touches {:

colorBlue = colorBlue + floatColorAdd

player?.color = UIColor(red: 0.8, green: 0.0, blue: colorBlue, alpha:
1.0)

To test the code, run the simulation. Every time you click on the display, the square will become more purple-ish.

We can actually take this concept to another level. For example, declare two new variables:

var colorRed : CGFloat = 0.85
var floatColorSubstract : CGFloat = 0.05

In the override function touchesBegan, change the Red value from 0.8 to colorRed. In addition, below colorBlue = colorBlue + floatColorAdd, type:

colorRed = colorRed - floatColorSubtract

By running the simulation and clicking on the display, you will notice the square’s changing color more rapidly from red to blue. This is because we are both adding blue and subtracting red. The ability to change color is useful when you’re a game designer because it gives you the ability to mimic nature. Just like some animals change color when they are threatened, so can characters in your game. This is just one of the many benefits of being able to manipulate colors in XCode.

To learn even more coding for FREE, check out our 30-minute introductory course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

Make an iPhone App in Minutes in XCode: Swift Crash Course (Free Tutorial)

iPhone apps are the rage these days. In this tutorial, you’ll learn how to make an app in just minutes! For more FREE coding lessons, check out our 30-minute beginners course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

We’ll also go over how to store items in a variable and set up a print button. Once you have XCode open, go to iOS > Application, and open up a Single View Application. For Product Name, type in “Simple Name app for iPhone p00”.

p00 is the production number, which are helpful to add whenever you are prototyping. Click Next and then Create.

In the left-hand sidebar, go to Simple Name app for iPhone p00 >Main.storyboard. Main.storyboard is where we can drag our elements visually onto the screen.

Click on the background so that it is outlined in blue. In the right-hand sidebar, change the size to “iPhone 5.5-inch”. This way our design will run on the simulator. You can also change the background color to, for instance, lead.

In the bottom right corner, enter “text” into the search bar. Drag and drop the Text Field element that appears onto the iPhone display. This is where a user will be able to input their name. Today we’ll learn how to transfer the input name from the Text Field all the way down into a label.

You can play around with the design of the box like I did: in the right sidebar, select the leftmost Border Style. In the colors tab that appears, click on the second icon from the left. In the Gray Scale Slider, make the brightness 95%. Also make the background color mercury.

Furthermore, in the right sidebar, go to Font, and select Custom. Below that, in Family, you are able to select a font, such as Futura. I’m using a font size of 40 and centering the text. Click Done when you’ve settled on a font style.

Beside “Placeholder” in the same sidebar, write “Enter Name”. That text will show up on the iPhone display.

Additionally, we’ll add in a button. In the bottom right corner, enter into the search bar “button”. Drag and drop the Button element onto the display, beneath the placeholder. Drag the corner of the button to resize it until it is the same width as the placeholder. Blue lines (rulers) will show up to help you measure an accurate size.

In the right sidebar, change the font of the text in your button to your desired font. I have selected Futura, size 67. In the right sidebar, just above where you determine your font, there is a bar saying “Button”, which represents the text inside the button. Change it to “Print Name”, and center it.

To set the background color of the button, scroll down in the right sidebar, and click on “Background”. Then go to the crayon box, and make the background tangerine. Close the Colors tab.

In the right sidebar, click on the Text Color bar. Let’s change the color of the text to lead.

Our third element is a label. In the bottom right corner, enter into the search bar “label”. Drag and drop the element onto the display, beneath the button. Resize it so that it has the same width as the button. For this example, let’s change the text “Label” to “Result” and center it. Also, let’s make the font of the text be Futura, size 35.

Now in the header, click on the assistant editor button, whose icon is two overlapping circles. Click on the rightmost icon in that header to remove the rightmost sidebar from the screen.

When you make something with XCode, you need to drag the items from the display into the code. In this case, we need to take in the data that the user will input, so we need to add a connection that is outlet.

To start, add some empty lines below the code line class ViewController: UIViewController {. Select the Enter Name placeholder, and drag it below that code line. On the tab that pops up, select “Outlet” for the Connection because we need to take in data that a user will enter. Name the object “txtEnterName”. Click Connect, and the following line will appear on your screen:

@IBOutlet weak var txtEnterName: UITextField!

In terms of the button, drag and drop it on a line above the final closing bracket of the entire code. Because we want this object to do something, we have to set its connection to “Action”. Give it the name “btnPrintNameACTION”. Click Connect to see the following appear:

@IBAction func btnPrintNameACTION(sender:
UIButton) {
}

Lastly, drag the label beneath the line @IBOutlet weak var txtEnterName: UITextField!. Set its connection to “Outlet”, and name it “lblName”. By clicking Connect, you will see:

@IBOutlet weak var lblName: UILabel!

Below that, we need to add in a variable, which is like a box into which you can put a piece of data. Using the keyword var, create the variable userName. Note that for the naming of variables, I am using camel casing, as per convention. In lower camel case, the first letters of every word after the first word in a name are capitalized. In addition, we can force the variable to be an empty string using the following format:

var userName : String = ""

When we print the button, we can add it in as a separate function. Above the last closing bracket, create a function like so:

func namePrintingLogic(){

}

To call that function, add namePrintingLogic() on a line above the closing bracket of the @IBAction function.

In the bottommost function, write the following line of code:

lblName.text = userName

But we have yet to specify the userName! On a new line above the previous one, type:

userName = txtEnterName.text

To summarize: a user enters a name. The user selects “Print Name”. The text will be stored in userName.

Load your simulator, and our display will appear. Click on Enter Name, and type in a name, such as “Mammoth Interactive”. Click Print Name to see “Mammoth Interactive” replace “Result”.

Congrats! I can’t wait to see the apps you create. To learn even more coding for FREE, check out our 30-minute beginners course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes

Adding a Sprite in Xcode SpriteKit: Swift Crash Course (Free Tutorial)

Have you dreamed about making millions with your own popular iOS game? Well, if you’ve ever wanted to design a game, the first thing you’ll need to build are graphics. In this tutorial, you’ll learn how to get started in SpriteKit and create your first sprite! 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. You will be prompted to choose a template, and there are different kinds of applications. The one we’re looking at today is the iOS application, which is specifically 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. Let’s immediately run the simulator to test that the project loads correctly.

In the left sidebar, open “GameScene.swift”. Because we’re going to be building our own sprite from scratch, delete 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 begin placing a sprite! A sprite is a 2D bitmap graphic that’s part of a larger scene. On a new line above override func update(currentTime: CFTimeInterval) {, add in a function using the keyword func. Name the function spawnSprite.

func spawnSprite(){

}

Within the override function didMoveToView goes the code that starts when the game starts. Add spawnSprite() on a line below override func didMoveToView(view: SKView) {. This will call the spawnSprite function, which will then create a sprite.

In order to spawn a sprite, you also need to add in a variable using the keyword var. On a line below import SpriteKit, create the variable mySprite, and set it equal to SKSpriteNode:

var mySprite = SKSpriteNode?()

This is what our sprite will be. Back within the function spawnSprite, add this line:

mySprite = SKSpriteNode()

Within the parentheses, you can add different items. For instance, if you want to have a Sprite with an image in it called Spaceship, you can insert the following into the parentheses: imageNamed: "Spaceship". This would correspond to the image “Spaceship” that you would have in the Assets.xcassets folder under “Getting started with SpriteKit”. You can drag and drop images from your computer into this folder.

Instead, let’s determine the color and size of our sprite within the parentheses. Insert the following into the parentheses: color: UIColor, size: CGSize. Let’s specify an orange User Interface (UI) Color, and a width and height of 40 pixels each. You can use the following format within the parentheses:

color: UIColor.orangeColor(), size: CGSize(width: 40, height:40)

Thus our sprite has a color and dimensions. Let’s now 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. Thus we have to set our sprite position equal to CGPoint. Furthermore, we can set our sprite’s position inside parentheses after CGPoint. Let’s say we want our sprite to be positioned in the center of the screen. You can achieve this by adding onto your existing line so that it looks like so:

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

Also, to spawn your sprite, type another line within the function:

self.addChild(mySprite!)

In addition, within the override function didMoveToView, we can also change the background color. To make our background an off-black color, for instance, type:

self.backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)

Editing the red, green, and blue values allows us to manipulate the background color. Note that alpha refers to the transparency. Run the simulator, and you will see a small orange square appear on the display.

You’ve successfully created your first sprite! You are on your way to making the next big game. To learn even more coding for FREE, check out our 30-minute introductory course here: training.mammothinteractive.com/p/learn-to-code-in-30-minutes