Devlog #3: Collision Detection
The third devlog of my shoot'em up game is up. This time I walkthrough my latest implementations regarding handling collision detection in Swift, SpriteKit and GameplayKit.
The third devlog of my shoot'em up game is up. This time I walkthrough my latest implementations regarding handling collision detection in Swift, SpriteKit and GameplayKit.
Physics Component (Collision Detection)
I now have everything I need when it comes to collision detection. I’ve done it via a GameplayKit GKComponent
to give entities the required collision behavior. Adding the component to an entity configures a SpriteKit SKPhysicsBody
and the related bitmasks more or less automatically. And I am using a separate struct so I have a central place for me to define contact relationships between entity types.
To complement the PhysicsComponent
that handles collision detection I’ve also implemented a Swift protocol that entities can adapt to receive relevant notifications on collisions and act accordingly.
Game State Machine
Moving on, next we have game state machines. Right now I have a GameplayKit GKStateMachine
for each enemy and a GKStateMachine
for the player. Just to get my feet wet with the pattern and have an initial implementation up and running. This turned out to be pleasantly simple to implement with Swift.
When the player receives a contact notification with an enemy it enters the take damage state. Once the contact ends it goes back to the normal state.
An enemy right now has three states, the normal flying state, the exploding state when hit by a bullet and then the dead state when the explosion has finished running.
I'm thrilled to see how organized the code turned out to be when using game state machines and putting logic in GKState
classes.
Remove Component
Following the Entity Component System design pattern, I've implemented a GKComponent
that is responsible for completely erasing entities from the game when they are no longer needed. The RemoveComponent
. This is completely handled on a background thread for performance. When an entity reaches its end of life in the game I just add the RemoveComponent
and be gone.
Bullet Movement Component
I’ve also added a GKComponent
responsible for bullet movements. Previously I had just hardcoded the speed and direction into the bullet sprites. That is now replaced with a component that handles the movement logic. The BulletMovementComponent
. Visually it still looks the same, but now I have a place for implementing and handling interesting bullet patterns. This will start to show its benefits when enemies get the firing ability.