Load the Textures

Apple Game Frameworks and Technologies — by Tammy Coron (33 / 193)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Create the Player Class | TOC | Control Render Order with Z-Pos ition 👉

Remember, a texture is nothing more than an image, or a visual representation for your sprite. To animate a sprite in SpriteKit, you can load an array of textures and cycle through them. Given this is something you’ll do a lot, it makes sense to use an extension[24] to load the textures.

Extensions, which are common to many programming languages, are a great way to reuse code, keep things organized, and extend the functionality of an existing class. To keep your code further organized, you’ll put the extensions into a separate file.

Create another new file (⌘N) using the iOS Swift File template. Name the file SpriteKitHelper.swift and replace its contents with the following:

​ ​import​ ​Foundation​
​ ​import​ ​SpriteKit​

​ ​// MARK: - SPRITEKIT EXTENSIONS​

​ ​extension​ ​SKSpriteNode​ {

​ }

You’re now ready to add your first SKSpriteNode extension method. Within the brackets ({}) of the SKSpriteNode extension, add the following code:

​ ​// Used to load texture arrays for animations​
​ ​func​ ​loadTextures​(atlas: ​String​, prefix: ​String​,
​ startsAt: ​Int​, stopsAt: ​Int​) -> [​SKTexture​] {
​ ​var​ textureArray = [​SKTexture​]()
​ ​let​ textureAtlas = ​SKTextureAtlas​(named: atlas)
​ ​for​ i ​in​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.