top of page

Unity Subclass Sandbox Pattern Snake with Abilities

This is an implementation of the Subclass Sandbox Pattern on Snake using Unity. I utilized the Subclass Sandbox Pattern to add three abilities to the snake: Speed Up, Slow Down, and Jump.

Specs
Date
Role
Team Composition

Unity

PC

Subclass Sandbox Pattern

01/2024

Game Programmer

Programmer * 1

Details

The Subclass Sandbox Pattern:

I chose the Subclass Sandbox pattern to implement different abilities for my Snake game. The reason why I chose it is simple: The Subclass Sandbox is perfectly suited for this use case.


Assets/Scripts/Abilities/Ability.cs:


The Ability class is the base class of all abilities. It has an Activate() which is mandatory for overriding, and Deactivate() and BodyColor to be overridden optionally.


When the subclasses are instantiated, they have to pass in the reference of the snake for the constructor of the base class. This is for avoiding the Singleton pattern.


The Ability class has three utility functions: SetColor(), SetSpeedMultiplier(), and MoveHead(). They are all used in combinations in the abilities.


Input Buffer:

I used the Update() within the Snake.cs to handle inputs, and FixedUpdate() to handle the actual movement, or say, physics.

The reason why I used the Update() for handling inputs is that I believe the inputs require the minimum amount of latency. And putting it in the Update() avoids the situation where an input get missed.


The reason why I put the actual movement handling in the FixedUpdate() is that the movement performance should be consistent among any devices. For example, if I use the Update() to handle movement, the movement speed on a 60 Fps device could be twice fast as that on a 30 Fps device. Although utilizing the delta time could avoid that problem, I chose the FixedUpdate() for simplicity.


I designed an input buffer system. When an input is made, the system stores it to be used for the next movement in the FixedUpdate(). And if another input is made before the system consumes the first input, it will be cached and be used for the next movement after the movement of the initial input. Any more inputs will override the cached second input.

bottom of page