Build a Monster Generator

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Create Your First Entity | TOC | Animate the Monsters 👉

The monster generator is what you’ll use to periodically spawn new monsters of a certain type at specific locations within the dungeon.

In the Project Navigator, select the Components group, and inside that group, create a new file (⌘N) using the iOS Swift File template. Name the new file GeneratorComponent.swift and replace its contents with the following code:

​ ​import​ ​SpriteKit​
​ ​import​ ​GameplayKit​

​ ​class​ ​GeneratorComponent​: ​GKComponent​ {

​ ​override​ ​func​ ​didAddToEntity​() {

​ }

​ ​override​ ​class​ ​var​ supportsSecureCoding: ​Bool​ {
​ ​true​
​ }
​ }

Because you won’t be overriding any of the other standard methods in this component, you can omit them.

Also, because you’ll be doing a lot with components — both in code and by way of the Scene Editor — it makes sense to create an extension to better manage the underlying node of the entity.

Creating a Component Extension

You may have noticed that in the health component you created in Create Your First Component, there was some duplicated code — specifically in regard to verifying that an underlying node exists. Rather than recreating the wheel in every component you make, you’ll create a GKComponent…

--

--

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.