Learn iOS with Examples, Code Snippets and Video Tutorials

How to Write Your Own Custom Classes in Sprite Kit

How to Write Your Own Custom Classes in Sprite Kit

First lets make a new Swift file. Go to File > New… > File.

Create a new Swift File for Your Custom Class

In this example, I’ll call the custom class Player.swift.

Create a new file named Player

Be sure Targets is checked off for whatever your project name is.


Making a Subclass of SKSpriteNode

Add the following code to your Player.swift

So now our Player class has all the same properties of SKSpriteNode. So even if we did nothing else at this point, we could write this in our GameScene class…

Initializing a custom SKSpriteNode class

Notice that after writing Player(  we start to get the same suggested initializers for an SKSpriteNode.


Adding Our Own Properties and Functions to the Subclass

Head back to your Player.swift file and add this code…

Now our class has one property runSpeed and one function, makeJump().

Back in our GameScene.swift we could now write this in the didMove function…

In other words, we initialized a new instance of the Player class with an image asset named “PlayerArt”. We then added it to the scene. And finally we set runSpeed to 10 and called makeJump.

How to Set a Custom Class for a Sprite in the Scene File (SKS)

After adding a Color Sprite to the scene, locate the Custom Class tab (circled in the image below), then add your class name. You don’t need to set anything for the Module file.

How to Set a Custom Class for a Sprite in the Scene File (SKS)

Give your Sprite a Name as well. You can see below we’ve named the Sprite “Player” as well.

Casting with Swift and Sprite Kit

Now, you’re ready to do some casting. You can read a more detailed explanation on casting here, but here’s how it will look in your GameScene file…

In case you’re curious, these screenshots come from our Role Playing Games video tutorial series which teaches how to make an entire RPG game from scratch using Swift and Sprite Kit.

 

Check out our premium Swift and Sprite Kit Tutorial content!

Visit CartoonSmart.com