Extending States in Javascript

Creating States in Javascript

Games always contain at least one Kiwi.State. The typical way to create a state using Typescript is to extend the Kiwi.State object.

States have a number of methods that may be called during the game loop, such as preUpdate, update, and postUpdate. Often, developers will want some of the work done by the base class, and some done by the derived class. For instance the update function will usually include a call to the bases classes update method (this will call the update method on each member of the state).

Something else to consider about states derived from the Kiwi.State class  is that they are almost never extended themselves, and usually only one instance is created of the state.

So when it comes to deciding how to create states in javascript we can take both these into account.

  • We need access to the super class.

  • The state we create will be a non-extended single instance of Kiwi.State. (if this is not the case then other methods may be necessary)

Because Javascript allows you to add properties to objects dynamically, it is very easy to get the functionality we need to extend the class in the case of States.

First we can create a new state instance.

This serves the same purpose, though does not do exactly the same thing as, the Typescript

There are three things we may want to do with the state. Use an existing property or method, create a new property or method, or override a property or method.

Using existing properties and methods is straightforward

Creating new properties is also easy. Simple add it dynamically

Note that this will add myNewProperty property to the myState instance only, and won’t affect the base class in any way. It’s ok to do this, because in this case we don’t ever need more than one instance of myState.

The final and least obvious thing we need to do is override methods and also call the methods we are overriding on the base class. In this case the Typescript:

becomes the Javascript:

Full Examples

The following code collects together these concepts and shows the creation of a state, the addition of a new property and method, and calls to the base class.



Share the joy

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">