Countless KiwiJS Games

Can you ever have too many games? We don’t think so. Check out what we’ve been up to recently. Hint: there are a lot of games.

For starters, we’ve got some technical talk about running multiple games on the same page. Then we’ll talk about GameDash2D and how we made a runaway hit in 2 days with KiwiJS, GameFroot, and a little help from Poland.

Running Multiple KiwiJS Games

User jdrorrer over on GitHub asked about garbage collection on entire games. We took a look and came up with some advice on how to run multiple games at once.

Why use multiple games? Well, sometimes you don’t need an entire screen full of moving graphics. Sometimes you might not even want a “game” as we know it. You can use KiwiJS to add programmatic detail to a website, like an animated helper in a corner, or glimpses through a window into a busy world behind your page. Or perhaps you only want the game to pop up at certain points, and otherwise use other HTML5 technologies better suited to the current task.

In these cases, it’s not a good idea to make a single huge game canvas and spread it across the page, or keep a game running when it’s not needed. That’s a good way to bring a browser crashing to a halt. If you need several little regions, make several little games. If you need a game to run only on demand, create it when needed, then destroy it to free up system resources.

We’ll discuss some things to bear in mind when using KiwiJS games in this way.

Best Practice

We recommend that you use an iframe to contain each game. With a little DOM manipulation, you can add and remove iframes quickly and reliably.

This is the technique that we use on this very website.


You may run into some dangers if you try to use multiple games at once. Here’s what to look out for.

First and foremost, browsers can’t provide a large number of contexts per document. We use an audio context and a graphics context per game. There is a limit on each type – in the case of our tests, it was 6.

Fortunately, if you put each game inside an iframe, it has its own document and never has to share contexts. We recommend that you always keep multiple games partitioned in their own iframes.

Second, don’t reuse states between games. You might find this happening if you’re creating, abandoning, and recreating a game using the same states. We don’t support the reuse of states in this way, because KiwiJS is set up to create and run a single game instance. States and filestores contain references to a single game. If they are then fed into a second game, they’ll try to access data on both games, and very likely crash the game immediately.

You should always treat different games as different games, whether they are separated in space or in time. Feel free to pass information between them using JavaScript, but we recommend that you keep all your actual game objects safe in their own little code area.


Did you know that KiwiJS has a sister project called Gamefroot? It’s a fast, easy, and fun way to create and publish games. Using the Gamefroot site, you can lay out whole levels, create code with drag-and-drop logic, and test your game online.

And it’s all done with KiwiJS.

When you’re done with Gamefroot, you can export your games as KiwiJS files. Gamefroot logic is powerful and corresponds closely to JavaScript, so you can start to code in Gamefroot and polish it by hand in your text editor of choice.

But don’t take our word for it. The proof of the pudding is in the eating, and the proof of the game maker is in the games.

So we sat down and made a whole bunch of games in just 2 days each. And we mean we made games – from planning to publishing on Google Play and iTunes, all within 48 hours per title. We even found time to sleep!

Check out our achievements at GameDash2D.


Some personal favourites include:

Absolution Velocity

This is an intense game of skill and split-second timing. Move your paddle by tilting your device, and try to slam the ball past the opponent. Eagle-eyed readers will note that we made a version of Absolution Velocity last year, but we’ve rebuilt it to use new controls, support online leaderboards, and give better visual feedback. It’s a whole new experience on mobile devices.

Freeway Fury

Two players face off across the same device, struggling to pull ahead in a post-apocalyptic drag race. We love the aesthetic on this game, and it’s a blast to play. We used Gamefroot to prototype the design, and coded the rest of it in KiwiJS. It’s super useful to have an interactive, logic-powered preview system at your fingertips!

Celebrity Breakout

Pop pimples on famous people. It’s as simple – and deliciously disgusting – as that. And we’ve had over a hundred thousand downloads, mostly in Poland.

We’d like to thank Poland for putting their faith in us, and we hope you enjoy the updates we’ve made to the game after discovering its popularity. We love the ability to build and adapt games so quickly. It means we can test and share ideas rapidly, and build on those games that people just can’t stop playing!

I’ll Hold ‘Em Off

Blow away zombies. Make quips. Meet a glorious death in battle. It’s the zombie apocalypse and you’re shooting as fast as you can, reducing wave after wave of monsters to a fine green mist. How long can you hold out?

I’ll Hold ‘Em Off features a “virtual joystick” system coded entirely in Gamefroot. Touch and drag anywhere to move; tap anywhere to shoot. Gamefroot gives you deep control over input and logic, with an interface that’s simple for beginners and powerful for pros.

Working with Gamefroot and Collaboration

Gamefroot is great for prototyping, but what happens when you want to have several people building game systems at once? Two people can’t edit the same document at once.

The solution is to think with objects. When you create game code in Gamefroot, it’s done with Google Blockly. This code can be exported and imported into other projects, using buttons at the top right of the code editor interface.

We found it productive to design self-contained game logic objects in our own documents, then share the exported code and import it into the master game. For example, one person would design the input system, while another would design bullet physics.

When it comes time to combine the systems together, we take advantage of the Gamefroot messaging system – and a whiteboard in the office. Once we’ve agreed on the name of a message, we can code our systems around that interface. For example, the input and bullet systems designed above would interface when the input object broadcasts a message of “BANG”, and the bullet is coded to fire when it receives the message “BANG”.

You can even call return functions on other game objects with what we call a “Request/Provide pair”. This uses the ability to send a value with a message. For example, I might send a message “REQUEST_PLAYER_HEALTH” with the value myself (meaning the object sending the message). The player object has a receiver for the “REQUEST_PLAYER_HEALTH” message and a value. This sends a message to the value (which is the original object) reading “PROVIDE_PLAYER_HEALTH”, plus a new value. Then the original object receives this message and the new value. It’s a bit more involved than a standard function call, but it’s very modular, and like all Blockly code, it’s very hard to cause errors.

Coming Up

We’ve got more on the horizon, so make sure you keep an eye on us. KiwiJS version 1.4.0 is now in the planning stages, and it’s going to reflect months of game production and community feedback. Look forward to it!

KiwiJS v1.2.0 – Kiwi.Log Debug System

Hello, and welcome to a new feature in KiwiJS v1.2.0! Today we’re looking at debugging – a vital part of any development cycle, and one which is much more powerful in this release.

It’s time to put console.log to bed. Say hello to Kiwi.Utils.Log, a more powerful way to manage your debug output.

An Introduction to the Console

If you have never developed with a console before, now’s the time to start. The browser console is a place where you can see messages and execute code.

The console is located in a different place in each browser, so you may have to go looking. On my desktop, Chrome provides it in the menu “View->JavaScript Console” or by clicking the menu button and selecting “More tools->JavaScript Console”; Firefox has it under “Tools->Web Developer->Web Console” or by clicking the menu button and selecting “Developer->Web Console”; and Safari has it under “Develop->Show Error Console”.

Not only does the console show you messages and logs from your code, it can also accept code input directly. This is very useful for tweaking behavior on the fly, looking up properties of objects, etc.

This article continues on the assumption that you understand the basics of the console.


Debug logging is inherently messy. You’ll probably want to insert debug code into many lines, and it should be as fast to type as possible.

We’ve added a convenient alias to Kiwi.Utils.Log. You can access everything via Kiwi.Log, and in fact that’s what we do in KiwiJS itself.

If you want to go even faster, add this at the start of your game:

Basic Output

Based on console methods, Kiwi.Log has three ways to output messages. You can log, warn, and error.


Logs are simple feedback messages. In most modern browsers, they will report the source file and line number on which that log was executed. You should use this for most purposes.


Warnings should appear differently in the console. Most browsers will put a warning sign next to them. In Chrome, they are conveniently yellow, which stands out against other logs.


Errors are more significant messages. They usually appear red. In addition, they will typically report a stack trace. This is a very useful output, which tells you not only what line was executed, but the line of every function that took it to that point. Errors and stack traces are excellent tools for figuring out exactly where you are in your logic flow.

An error will not interrupt your program. It’s just a special kind of log.

Concatenated Output

You can supply any number of arguments to output methods.

Using Tags

You can add tags to your logs to aid in filtering. It’s simple: just add a string starting with a hash (#). Any such string in the arguments of a log method will be recorded as a tag.

Note that a tag must start with the hash. Only that character is checked.

Showing Logs

Logs are recorded. You can go back and access the records using various techniques.

Filtering with Tags

Any show method can take tags, just like an output method. This will restrict its return to only those messages that include that tag.

If your game contains lots of debug messages, tags are a great way to filter through the mess.

Stack Trace Warning

When accessing recorded logs, stack traces are no longer accurate. This is because they are no longer being executed in their actual place in the code. You should always consult errors in-situ.

Methods for Showing Logs

You can use the following methods to show logs:

  • showAll() displays the entire log.
  • showLogs() displays all messages logged with log().
  • showWarnings() displays all messages logged with warn().
  • showErrors() displays all messages logged with error().
  • showLast() displays the last message logged. If you specify tags, it will display the last message logged with that tag.
  • showTimePeriod() displays all messages logged within a certain time range. This uses a Unix time, measured in milliseconds since 1970-01-01T00:00. This is currently 1.422 trillion, which is a difficult number to handle. We recommend you specify the time range as milliseconds before now, for example Kiwi.Log.showTimePeriod( - 10000, - 5000 ) to show all logs from 5 to 10 seconds ago.

Configuring Output

Logs are useful during development, but they have little purpose after the product ships. You should probably remove all debug code for your release build. However, if there are good reasons to maintain it, you can at least prevent it from clogging up the console.

Set Kiwi.Log.display = false to mute all output. The log will still be recorded, but it won’t be displayed in the browser console.

Set Kiwi.Log.record = false to disable recording. The log will still be displayed, but it won’t add any more records.

Set Kiwi.Log.enable = false to disable the log entirely. You can still access records, but messages will not be printed to the console, and the log will not record anything more.

Be careful with logs. Your game updates some 60 times per second, and logs can very rapidly become very large. It’s trivially easy to push so much data into your console that the whole browser freezes. By configuring your output, you can avoid this inconvenience.

Game Designer’s Log, Supplemental

We hope you find this new tool to be useful. It’s a big step forward for controlling and recalling your debug process. Now set course for the undiscovered country of future productivity – second star on the right, and straight on til morning.

That’s it for KiwiJS v1.2.0. We’ve covered all the cool new bits. But as always, there’s plenty more on the horizon! Stay tuned for the next great adventure.

KiwiJS v1.2.3 Available

Easy as 1-2-3, here’s the latest KiwiJS fix release.

You can download KiwiJS from our GitHub repo.

This release incorporates the following:

  • Clock.elapsed() now resets to 0 after start() is called.
  • Geom.Intersect.lineToLineSegment and lineSegmentToLineSegment now work correctly.
  • Entity.inputEnabled wasn’t used by anything, and is now officially deprecated.

Let us know what you think on the website!

KiwiJS v1.2.0 – Color Object

Hello, and welcome to a new feature in KiwiJS v1.2.0! Today we’re going to take a look at the new Color object, a unified color paradigm for KiwiJS games. This object is very simple, but has a panoply of ways in which it can be used.

Introduction to Color

Create a Color object as follows:

You may alter a Color object after creating it as follows:

You may access colors on the object as follows:

However, this is just the tip of the iceberg. There are many more ways to phrase data for color.

Note: Native Normalized Color

The Color object uses normalized color internally. It has four channels (red, green, blue, and alpha) in the range 0 (black) to 1 (maximum brightness). We use normalized color because it is most mathematically convenient. It is used in WebGL for this reason, and we like to maintain this compatibility.

We recommend that you work with normalized color whenever practical.

Advanced Color

There are a very large number of color formats in use today. The Color object can cope with a good number of them. In this section we’ll show you as many formats as we could fit in there.

Important note: No matter what format you put in, you can always get it out in any other format. Color objects are converters as well as storers.

RGBA Formats

These formats record color as four channels: red, green, blue, and alpha (transparency). In the wild, these may be treated as normalized channels (0-1), or as 8-bit channels (0-255).

You can access these channels in these ways:

  • color.r, .g, .b, .a: Normalized color (0-1).
  •, .green, .blue, .alpha: Normalized color (0-1).
  • color.rNorm, .gNorm, .bNorm, .aNorm: Normalized color (0-1).
  • color.r255, .g255, .b255, .a255: 8-bit color (0-255).

You can set the channels in exactly the same way.

However, the channels color.r and (etc) are “smart” setters. If you pass a number between 1 and 255, they will parse it as an 8-bit number instead. This should rarely be ambiguous. Only when an 8-bit number is precisely 1 will you encounter problems. In this case, we recommend that you work universally with normalized channels, or use .r255 and .rNorm to avoid ambiguity.


When you create or set a Color, you may pass it parameters. By default, these are interpreted as RGBA channels using “smart” setters. For example, color.set(1,0,0) (without an alpha channel) will create solid red, and color.set( 127, 127, 127, 127 ) will create transparent gray.

Note that the channels are parsed separately, so you could recreate transparent gray as color.set( 127, 0.5, 0.5, 127 ). This is confusing. Why would you do that?


These formats record color in a different way. They store hue, saturation, and either value (or brightness) or lightness, along with an alpha term. HSV and HSL are not the same thing. We recommend you read up on the formats, for example on Wikipedia.

As with RGBA, we recommend the use of normalized values. Values above 1 are parsed differently. Hue is always parsed in the range 0-360; saturation, value, and lightness are always parsed in the range 0-100; and alpha is always parsed in the range 0-255. It’s a little confusing, but it’s standard.

You can call the following methods to set HSVA or HSLA colors:

  • color.parseHsv( h, s, v, a ): Set color in HSV format, either normalized or not. Alpha parameter is optional.
  • color.parseHsl( h, s, l, a ): Set color in HSL format, either normalized or not. Alpha parameter is optional.

You can call the following methods to get HSVA or HSLA colors. Both methods return an object with normalized values.

  • color.getHsva(): Returns object { h, s, v, a }
  • color.getHsla(): Returns object { h, s, l, a }


When you create or set a Color, you may pass it parameters. Append the string "hsv" or "hsl" (lowercase verbatim) as the last parameter, and the color will interpret the values accordingly.

For example, color.set( 0, 1, 1, "hsv" ) is solid red, and color.set( 180, 100, 100, 50, "hsl" ) is translucent white.

CSS Formats

These formats record color as a string: either a hex color code or as a function. The color object can interpret these formats and apply them.

All these formats can be interpreted by the method color.parseString( string ). If you are using a hex string, you may pass it directly to color.parseHex( string ).

You may specify color as a hex string. This is a flexible format. Valid formats include "fff", "ffff", "ffffff", and "ffffffff". They may be uppercase or lowercase. You may begin the hex string with "#" or "0x", but this will be stripped off.

The hex string evaluates to RGB or RGBA numbers, either as 4-bit or 8-bit channels. For example, "f00" equates to ( 1, 0, 0 ), while "4080ffff" equates to ( 0.25, 0.5, 1, 1 ). (It’s actually not quite, because bit channels don’t divide neatly.)

You may specify color as a function. This is in one of four forms: "rgb(r, g, b)", "rgba( r, g, b, a )", "hsl( h, s, l )", or "hsla( h, s, l, a )". The Color object will determine which form is in use, strip off the wrapping text, and pass the parameters to the respective setter (RGBA or HSLA).

You may also extract the color value as a hex string. Call color.getHex() to get an RGBA color ("ff8040ff"), or color.getHex( false ) to get an RGB color ("ff8040").

Restrictions: You cannot extract color as a function. You cannot specify CSS color keywords (for example "cyan").


When you create or set a Color, you may pass it parameters. If the first parameter is a string, it will parse it as described above.

Using Color In The Field

KiwiJS now uses Color objects internally. Key implementations include Stage.color and TextField.color objects.

To maintain API compatibility, these colors still return hex strings. They were designed separately and use their own formats, so the Stage reports "ffffffff" while the TextField reports "#ffffffff". This will definitely be fixed in v2.0.

Fortunately, you don’t have to wait that long for input to be fixed. Both objects will happily receive any valid Color.set parameters. They even understand each other.

Note that if you are using multiple parameters, you must wrap them in an array.

For example, there was once only one way to make text black: text.color = "#000000". But now you can use many different methods:

Thank You!

We hope you enjoy using the new unified color system. There’s no need to reinvent the wheel, even if it’s a color wheel. We’ve settled on normalized color as best practice, but with the Color object, you can use whatever you like. And if we’ve forgotten some arcane color format, drop us a line! We’d love to hear about it.

Next time: Keep track of it all using Kiwi.Log!

KiwiJS v1.2.0 – Improved Clocks and Time

Hello, and welcome to a new feature in KiwiJS v1.2.0! Today we’ll be doing the Time Warp (again?), taking a long look at Clocks and all the new things they can do to control your game.

The Clock code isn’t restricted to just clocks, of course. It includes upgrades for animation, timers, and tweening, which in turn can control just about any part of your game.

At the end of this article, we’ll discuss best practice when it comes to time. You can save yourself a lot of pain if you develop with a full understanding of time and the tools available to control it!

Time Hierarchy

We’ve given time a real overhaul in KiwiJS v1.2.0. Just how major an upgrade is this? Let’s take a look.

Old Time

Once upon a time, there was one clock, and it was either playing or not playing. Time flowed something like this:

  • Master Clock
    • Game Clock
      • Animations
      • Timers
      • Tween Manager

There are several issues with this system. For example, say you want to pause the game. Pause the Game Clock, and all your animations and tweens will stop. But what if you have a beautiful animated UI, with tweened transitions and animated buttons and special effects? None of that will play while the Game Clock is paused. You could always put a check on everything that refers to a universal pause variable, but now we’re back to something a lot more complex than

New Time

In KiwiJS v.1.2.0, we’ve turned the clocks up to 11. Here’s an example of a new hierarchy:

  • Master Clock
    • World Clock
      • Animations
      • Timers
      • Tween Manager
      • Rate
    • UI Clock
      • Animations
      • Timers
      • Tween Manager
      • Rate

Immediately, you can see that everything is better. Pause the game world by pausing the world clock, and the UI remains intact.

But you can do even more cool stuff.

Using Clocks

Clock Management

To create a new Clock, use the game’s clock manager game.time.

And as simple as that, you’ve got two new clocks to play with.

Clock Properties

We’ve added some useful properties and methods to the Clock. These make it much easier to create smooth movement – and some other tricks.


The rate property was first introduced in v1.1.0 on ClockManager. It proved so useful that we’ve expanded it onto the clocks themselves.

rate is simply actual frame time divided by desired frame time. If the two are identical, rate = 1. If actual frame time is taking too long, rate > 1.When the frame rate drops, rate increases proportionally. Multiplying by rate makes your properties change at the same rate no matter what frame rate you encounter.

We strongly advise that any animation over time incorporate * rate to keep it smooth. This will also allow it to take advantage of other new time features.


Using rate lets you skip dead time and get on to where you should be by now. But sometimes that skip is just too massive. For example, if your browser hiccups and freezes for six seconds, you might not want to skip that far ahead in time. That’s long enough for characters to move through walls, jump halfway across the screen, and otherwise exhibit unwanted behavior.

We’ve implemented maxFrameDuration to fix these issues. By default, maxFrameDuration = -1 and has no effect. If set to a positive number of milliseconds, however, it will clamp the effective frame duration to that level. This prevents major skips.

We advise that you set maxFrameDuration during a state create method, not earlier. If you try to set it just after game creation, you may find that clocks have not yet been created.


This method returns the number of clock units (default: seconds) since the Clock was started. This does not include time spent paused. In the event that time runs backwards, the total will diminish.


Pay attention; this is awesome.

The timeScale parameter controls how fast time elapses on that clock. By default it is 1, which means time advances into the future at 1 second per second.

You can change timeScale. Set it to 2 to induce fast-forward. Set it to 0.5 to go into slow motion. Set it to 0 to freeze time. Set it to -1 to rewind time.

This is another reason why you should use rate in all your animations. If you are using rate, it will be affected by timeScale.

If you are running different parts of your game on different clocks, you can change the timeScale to create targeted temporal distortions. For example, you might drop a time bomb on an enemy and freeze them in place while the player’s speed is unaffected. Or you might send the whole game into slow-mo while your user interface remains at full speed.

The timeScale isn’t magic, and it isn’t a timeline. You can’t undo events or reverse physics. At least, not with the core library. timeScale is the foundation upon which you can build the most sublime paradox, should you desire it.


KiwiJS has a robust timing system, but it was always a little bit tricky to use. Here’s the old way of making a single-use timer event that prints a message after 1 second:

That’s a bit of an eyeful, isn’t it?

To fix this, we’ve taken inspiration from standard JavaScript functions. Clocks now have a setTimeout() method, which works very much like the normal browser version. It even uses milliseconds. Now you can simply call:

Much nicer.

The main difference with the KiwiJS setTimeout() is that it takes an extra optional parameter:

The context parameter defines the object which is this inside the callback. Experienced JavaScript developers will appreciate that this is often not this, so we make it easy.

You may also specify any number of arguments after context. These will be passed to the callback.


Just like setTimeout, setInterval() mimics the JavaScript command. It repeats a given callback function once per given number of milliseconds.

This will simply repeat the callback once every second forever and ever.

As both setTimeout() and setInterval() return a Timer object, you can store it and use it to clear the timer later. Unlike basic JavaScript, there is no “clearInterval” command. You should simply use the standard Timer management systems:

Using Other Time-Based Features

Clocks are cool, but they just give out time. Other features actually use it. Let’s take a look at some of the new things you can do in v1.2.0 with Animation, Timer, and Tween.


An Animation is a single sequence of spritesheet cells. It is stored in an AnimationManager. Upon playback, the game will display cells one by one, switching at a particular time interval.

There’s that keyword: time. Yes, an animation is controlled by a Clock. In v1.2.0, you can alter the flow of time, and the animation will play back at the altered speed. You can even reverse time, and animations will play backwards.

Note that if your animation does not loop and plays back to its own beginning, it will dispatch onComplete and stop.

In v1.2.0, animations will automatically use the Clock of their entity. If you set the Clock directly on an animation, it will use that clock instead.

(In more technical terms, an animation will use a clock if it is set. If its clock is instead set to null, it will attempt to use this._parent.entity.clock; that is, the Entity of an AnimationManager. Animations are created with clock null, so this behavior is default.)


The Timer object executes TimerEvent objects after a time interval. We’ve added helpers to make Timer use simpler (see Clock.setTimeout and Clock.setInterval, above), and those should make everything much easier. However, there are some advanced tips that you might find useful.

Timers work on clocks. This means that you can pause and resume clocks, and all timers on that clock will respect that.

You can also alter the timeScale of a clock, and its timers will also respect that. There are some non-obvious consequences of this. When time runs backwards, a Timer will start “un-counting”. It will not fire events when played backwards.

Further, if a Timer rewinds to before its start time, it will clear its events and stop itself. This reflects the fact that, when time goes forwards again, game logic will probably add these events and start the timer again. Note that this can cause “orphan timers” to appear. An “orphan timer” is a timer that was scheduled to remove itself, such as in a setTimeout, but was rewound and cleared itself, so it will never remove itself. That orphan will sit on the clock doing nothing forever. If you are using negative time, you must audit your timers, or you may get unexpected accumulation and slowdown.

Tween and TweenManager

A Tween is a one-off transition from one number to another. It’s usually used for animation, but it can be applied to any number on any object.

Tweens use time. In previous versions of KiwiJS, they used game.time.clock exclusively. We’ve upgraded them in v1.2.0 to use any clock.

Tween are created on a TweenManager, so that’s where we set the clock. For example, if you were creating separate tweens for world and UI space, you might do this:

You may now call these new TweenManagers to obtain tweens that use custom clocks. You can pause, resume, and timeScale these clocks as you wish, and the tweens will follow along.

Because a Tween is a one-off, it should not act outside the bounds of its duration. Accordingly, if you rewind time to before the Tween began, it will consider itself finished, and signal itself for removal. (It will not fire its onCompleteCallback signal, however. This will only fire if it finishes at the end.)

Best Practice

We’ve spent a lot of time working with time, and we have some recommendations that will help you create to your full potential. These guidelines will help you create an integrated, functional timespace that is easy to control and to understand. You don’t need to be making a time-warp game to use these practices; they’re a good idea even for basic animations.

Use Time for Everything

You may think this goes without saying, but it’s an important guideline. There are many ways to animate your game world, and all of them seem to give you time-based animations, but some are more reliable than others.

For example, if you have a line that reads this.rotation += 0.01, you might think that this will rotate an object at a steady rate. It will fire once per frame, and that’s nice and even, right?

I’m afraid you’ve fallen into my trap. Frames are supposed to be even, but in practice they often aren’t. Browser performance can change based on system activity, background pages, etc. This rotation might slow and chop at unexpected times.

Use Rate

If you iterate a number on a per-frame basis, such as in this.rotation += 0.01, you should always multiply by clock.rate. This number will compensate for any slowdown on the previous frame.

Ensure that you use the rate of a clock. The default game.time.rate cannot be controlled as well as clock rates.

Note that rate cannot tell you how long the current frame will take to render, because it hasn’t happened yet. We must estimate from the previous frame. However, it has the sum effect of keeping everything very close to where it should be.

Use Tweens

Tweens are handy aids. Whenever you want to perform a single movement, consider using a tween. For example, if you want to lower the drawbridge on a castle, use a tween. There are many flavours available, which you can see in our tween tutorial.

Use Timers

When you want to schedule events, just use Clock.setTimeout or Clock.setInterval. They’re easy and reliable, and they work with game clocks.

Use Custom Clocks

It’s hard to retroactively add clocks into a scene, so if you think you’ll ever need more than one, do it at the start. We recommend creating “world” and “ui” clocks at a minimum.

When you create a clock, you should also create an associated TweenManager that uses that clock.

When you create entities, make sure you set their clock property to the correct clock. This will ensure that their animations use the correct clock as well. It will also give them onboard access to the custom clock, which is useful for accessing rate.

Pause Efficiently

Now that everything in your scene is controlled by time, you can ensure that they pause with a single command.

As of KiwiJS v1.2.1, these are functionally identical, but each have unique considerations. The timeScale method allows you to tween pause on and off, creating a brief slo-mo effect. However, if you are also using time manipulation elsewhere in your scene, you may find it difficult to track both paused and manipulated time. We recommend you use clock.pause() unless otherwise necessary.

Use maxFrameDuration on All Clocks

The maxFrameDuration property can prevent excessive skipping if the frame rate is very low. We find that this will often happen on the first frame of a scene, right after loading, or upon returning to a web page game after visiting another tab. Game objects can jump far outside their predicted boundaries, disrupting gameplay.

Use maxFrameDuration = 500 to limit this skip to half a second. This is usually enough to prevent objects from jumping too far, but still permits smooth movement even in the event of very slow or irregular frame rates. Don’t forget that it is a per-clock property; you should set it on all your clocks at once during State.create.

It Is Time

You have learned much about time management today. We hope that it is useful. Understanding the nature of time gives you access to tools that make your life as a developer much easier. Please give them a go, and let us know how you get on! And remember – where we’re going, we don’t need roads. (Oh yeah, we’re subtle.)

Next time: All the colors of the rainbow, or at least anything that fits into an RGBA color space.

KiwiJS v1.2.2 Ready To Roll

We’re pleased to announce KiwiJS v1.2.2 is now available. This release fixes a number of bugs in animation and geometry.

Download KiwiJS v1.2.2 here.

Bug fix list includes:

  • Animation now correctly plays non-looping animations.
  • Animation.onPlay, .onStop, .onupdate, .onLoop, and .onComplete now correctly documented in API.
  • Geom.Intersect.circleToRectangle() and Geom.Intersect.lineToRawSegment() now work correctly in all cases.
  • Geom.Intersect.lineSegmentToRectangle() is now named correctly in API docs.
  • Geom.Line.perp() can now deal with points at (0,0) and other edge cases.
  • Added method Geom.Intersect.lineSegmentToRawSegment() to allow lineSegmentToRectangle() to function correctly.
  • Animation now correctly plays 1 frame animations and dispatches signals appropriately.
  • Utils.GameMath.nearestAngleBetween() now returns normalized angles so results are truly nearest.

KiwiJS v1.2.0 – Entity Component System

Hello, and welcome to a new feature in KiwiJS v1.2.0! Today we’ll be looking at the upgraded Entity Component System (ECS), and how it makes everything better.

What is an ECS?

In an ECS, all objects in a game world are represented as entities; their properties are represented as components; and the game has systems to update entities and components. See more details at Wikipedia.

A pure ECS will represent the entire world in this fashion. KiwiJS uses ECS philosophy only to extend the functionality of basic game objects. However, this is still a tremendously powerful tool in your arsenal.

In practice, this means that you can add a Component to a game object, and it will automatically go to work. You don’t have to call it; KiwiJS just knows to update components. This can be very useful for adding functionality to game objects in a one-step, it-just-works fashion.

NOTE: All Components Update

Components existed in previous versions of KiwiJS. Several game systems use components, including Animation and ArcadePhysics. However, due to a bug, they didn’t update automatically. A manual update was necessary for most components. Animation would update automatically thanks to a manual update within KiwiJS itself.

This is no longer the case. Any Component on an entity will update if active.

This makes code much simpler to write and maintain. However, be warned: if you have written manual updates for components, those updates should be removed. If you keep the manual updates, components will update twice per frame.

Working with Components

Creating Components

In KiwiJS, you can use components as follows:

  • Create Component
  • Add to entity

No further work is needed. The component will update automatically every frame.

You would do this as follows:

However, this component does nothing just yet. How can we add functionality?

Every Component has a blank update() method intended precisely for this purpose. You can override the update with your own function and it will be executed every frame.

This simple function is just the tip of the iceberg. The Animation and ArcadePhysics systems do a lot more work.

Managing Components

Sometimes you don’t want a component to function all the time. To control this, simply use its active property. When active is false, the game will skip updates on that component. When set to true, it returns to normal function.

If you want to remove a component altogether, use the entity’s component manager to remove it. Be warned, once removed in this way a component cannot be reused.

Advanced Flow: Pre- and Post- Updates

Sometimes you may want to run some type of component apart from the main sequence of per-frame updates.

For example, consider a game in which robots jostle for control of a hill. The robot at the top of the hill every frame scores a point. You could add a component that checks to see whether a robot is at the top and if so gives a point. However, this could yield incorrect results if another robot later pushes that robot aside during the same frame.

You can run updates before and after the main update. The Component has not one but three updates: preUpdate, update, and postUpdate. preUpdate is called just before the State updates. update is called at the start of the State update. (If you override State.update, as is common, this will occur when you call this ).) postUpdate is called after the State updates.

These functions can help you structure your flow without having to write complicated control loops.

For example, consider the following implied logic.

This component will process all the jostling for position in one pass, and then calculate the score. No positions will change during the scoring pass, so it will be perfectly accurate.

If you need more than these steps, we recommend that you create inactive components (so they won’t automatically update), register them to lists, and write loops to step through those lists. This is similar to the way in which components were handled in earlier versions.

Creating Custom Components

In many cases, you will wish to create entire prototypes for custom components. For example, your snail racing game will be much cooler if the snails leave mucus trails. Rather than code each snail with its own Component, you could create a single extension of Component and reuse that.

Here’s a template for creating custom components.

Advantages of ECS in KiwiJS

We see two big advantages to Entity Component Systems.

First, they are modular. You can apply only those components that you need. You don’t even have to check to see whether a given entity has a given component; you just update all its components, and they do the right job. We use this behind the scenes to differentiate between StaticImage and Sprite; the main difference is solely that Sprite has an Animation component attached automatically.

Second, they are low-maintenance. Have you ever written a big for loop that steps through everything in your scene to do something vital? With ECS, you don’t have to do that. You can just add a component to all the objects, and it will automatically update. This leads to lighter update loops in your State, and that makes for simpler code.

There are loads of other cool things you can do with ECS too, of course.

The Future

ECS is pretty exciting, and we’re looking to extend the philosophy. KiwiJS has always been about modularity and customisable game architecture. It’s safe to say that future versions will take this idea even further, allowing you to create self-perpetuating architectures faster and more conveniently than ever before.

Thank You

We hope you enjoy using the Entity Component System. Let us know how it works out, and also let us know if you have any suggestions for improving the system! We’re always looking to improve.

Next time: Set your controls for the heart of Time!

New Updates: KiwiJS v1.2.1, Particles v1.2.0

Announcing two new update releases in the KiwiJS family. KiwiJS v1.2.1 fixes some bugs, and WebGL Particles Plugin v1.2.0 updates the plugin to use KiwiJS 1.2.x standards.

KiwiJS v1.2.1 is available on Github. This is a patch release, resolving bug fixes and improving performance. It does not include new API functionality. Release notes include:

  • Animation could, under certain circumstances, freeze for a few seconds before playing. This was due to accidentally starting in 1970 and scrambling to catch up. This is no longer possible.
  • Clock.rate will now equal 0 if the clock is paused or stopped.
  • Correct documentation for TextField and Kiwi.HUD.Widget.MenuItem to show proper constructor information.
  • Non-looping animations now refer to the correct cells when played a second time.
  • State.create now fires after file loading is complete. Logs no longer overlap between loading and creating.
  • MasterClock now starts today, rather than 1970, avoiding anomalous results on first frame.

Update: The bugfix had a bug, which has been hotfixed. Downloads should now work properly.

WebGL Particles Plugin v1.2.0 is available on Github. This is a minor release, adding functionality. The main purpose of this release is to add compatibility with features in KiwiJS v1.2.x. Features include:

  • Upgrade to KiwiJS v1.2.0
  • Add setColor and getColor methods, allowing you to use Kiwi.Utils.Color style color values.
  • Add clock property to drive particle animation based on in-game rather than game-independent time
  • Config parser is stricter with numbers expressed as strings. It can find and correct most of these errors. This is not an issue in many browsers, but it has caused problems in CocoonJS.

We hope these releases are useful. Let us know how they work out!

Coming Soon: KiwiJS v1.2.0

We’re excited to announce that KiwiJS v1.2.0 is nearing completion. This version makes it easier to create games with awesome new features:

  • ECS (Entity Component System): Automatically update components on your game entities. Don’t waste time writing endless loops and checks in your state update – put components on objects and sit back.
  • Clock enhancements: Warp time to your pleasing with deeper access to clocks. Use helper methods to run timer events with a single command; pause a game clock and keep a UI clock running; and more!
  • Kiwi.log debug system: No more “console.log” calls clogging up your browser during development. Our powerful debug system supports muting, automatic tags, log recording, and more. If you develop with KiwiJS, Kiwi.log will make your life better – it’s that simple.
  • Battle-hardened performance optimization: We’ve been making games and we want them to go as fast as possible. Through extensive profiling we’ve picked out key upgrades to make games run faster on low-end devices where every processor cycle counts.
  • Plus a trailer load of enhancements and fixes to make your life better!

And that’s not all; we’ll have some extra surprises at launch.

KiwiJS has always been fast and powerful, but these upgrades shift into a new world of cutting-edge architecture. We’re looking forward to showing you just how efficient you can be.

Watch this space.

Grit your teeth – Damage Pipeline Plugin incoming

Tired of taking the same 10 damage? Want to introduce elemental weakness and resistance? How about stun damage, or energy shields, or a super meter that builds as you take hits? The new Damage Pipeline Plugin has you covered.

Connect nodes and meters, then dispatch packs into the pipeline. This plugin makes it easy to design and modify modular damage systems as you go. Create a fully functional health and armor system in less than 20 lines of code.

In this example, everything is controlled by a damage pipeline. The animation of the health bar, the text alerts, the changing status message… it’s all done by the pipeline. (With a little help from the Primitives Plugin, of course.) Note how we remain unscathed if our armor absorbs the physical blow, thanks to the ability to stack “sub Packs” representing dependent damage types.

To get started with the Damage Pipeline Plugin, check out our easy introductory tutorial.

Then download the Damage Pipeline Plugin from Github. We hope you make something amazing!