Chapter II in the series of tutorials on how to build a game from scratch with TypeScript and native browser APIs
Welcome back to the series “Gamedev Patterns and Algorithms in Action with TypeScript”! In this series, we learn the fundamentals of gamedev using a web browser’s API and TypeScript.
Last time we end up with the question: how can we start the Game Loop without overcomplicating the constructor. One of the approaches we could take is making it ‘awakable’’.
Feel free to switch to the
_game-loop-1_
branch of the repository. It contains the working result of the previous posts and is a great starting point for this one.
If you recall, we made significant progress setting up the game
entity. We even prepared its Update
method that recursively updates all components of the Game
. However, it is not much of a help since nobody makes an initial call to start the loop!
We also established that it is possible to start the loop with the help of constructor:
A better approach would be to provide a dedicated initialization method. This method can start the loop and do many other setups, while the constructor remains lean. We can call this method whatever we like, for example, Init
or Awake
. I will use the latest to mimic the Unity3d
API.
All Entities and Components will now become “awakeble”. That is: they will have the public Awake
method.
Note that this lifecycle method doesn’t have a strong relationship with a constructor. An object can be constructed only ones, while it’s
_Awake_
may be executed multiple times per the lifespan of an object. It can fall “asleep” and then being awaken again. One of the typical examples is reusing objects to avoid the cost of memory allocation of instantiating the object (read: executing constructor).
It is tempting to simply add a new method to abstract Entity
and interface IComponent
. But just as Update
, Awake
can be part of other elements of our game, not only ECS. It is wiser to create a dedicated IAwake
interface and then implement it.
#design-patterns #game-development #typescript #algorithms #javascript #algorithms