Create Your First Component

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Add the Resources | TOC | Create Your First Entity 👉

The first component you’ll make is a health component. The health component is a way to track the number of health points an entity has remaining.

To make a component using the GameplayKit framework, you need to subclass the GKComponent superclass (which is another way of referring to the base class or parent class).

Each component represents a single “trait” or “ability” that you can add to an entity, and an entity represents one of your game objects. The nice thing about components is that you can reuse and add them to any type of entity. For example, you can create a single health component that both your player and monsters can share.

Creating the Health Component

In the Project Navigator, below the Extensions group, create a new group (⌥⌘N) and name it Components.

Inside the new Components group, create a new file (⌘N) using the iOS Swift File template. Name the new file HealthComponent.swift, and replace its contents with the following code:

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

​ ​class​ ​HealthComponent​: ​GKComponent​ {

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

​ }

​ ​override​ ​func​ ​willRemoveFromEntity​() {

​ }

​ ​override​ ​func​ ​update​(deltaTime…

--

--

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.