Kiwi.JS HTML5 Game Engine Open source mobile HTML5 Javascript game engine Thu, 30 Apr 2015 05:05:30 +0000 en-US hourly 1 Particle Editor now live! Wed, 15 Apr 2015 22:49:17 +0000

We bet you want pretty particle effects, just like us. What’s not to love?

But there has always been one problem with particle effects. Creating them by hand can be a long and painful process, and while we have an awesome Kiwi.JS Particle Effects Plugin, defining an entire object literal and configuring all the options can still feel very confusing and overwhelming.

We are proud to announce the release of the Kiwi.JS Particle Editor. This online tool provides you with a easy to use interface for making particle effects that make your game pop!


The Particle Editor streamlines the particle creation process by giving real-time visual feedback for the options you can apply to particles.

To get started, simply go to and configure the particles using the the controls in the left sidebar.

You can read more about how to use the Particle Editor here.

Now go out, create that pretty particle effect you have visualized in your head, and let us know what you think in the comments below :)

]]> 1
Match Three HTML5 Blueprint Upgraded Fri, 20 Mar 2015 01:38:52 +0000 Hello to all. Today we are proud to say that, thanks to Uncle Zeiv, the Match Three Blueprint has received a massive rework. This blueprint was in need of update as it was originally created for Kiwi.JS version 0.6.0, which was so last year.

Have a play with the updated blueprint below and let us (and Uncle Zeiv) know what you think!

You can find and download the blueprint on github.


  • Greatly reduced code duplication.
  • Modular architecture with separated classes.
  • Clear documentation throughout the code.
  • Smoother animations using tweens.
  • Tile swap now animates.
  • Abstracted away logical coordinates to screen coordinates mapping.
]]> 2
Greetings from Kiwi.JS v1.3.0 “Moriarty” Mon, 16 Mar 2015 21:07:29 +0000 Hello readers. Today we are happy to announce the release of Kiwi.JS version 1.3.0, “Moriarty”. This release is named in honour of Brian Moriarty, designer of Loom, a fantastic fantasy game made by LucasArts in the 90s that inspired many of us here at the studio to embark on our game development journeys. “Moriarty” also sounds like you are talking to a cunning and dastardly villain, which we think makes it sound awesome.

This latest version of Kiwi brings new features to multiple areas of the engine. Instead of focusing on a particular area to upgrade we decided to add in a lot of niceties that we have always wanted, such as window focus/blur events, window visible status, passing parameters to State preload methods, plus much more.

You can download Kiwi.JS v1.3.0 on github now.

New Features

  • Window focus/blur events added to the Stage allowing users to easily pause/resume their game. (#23)
  • The Animation Component will now look for sequences on their given texture atlas if told to play a sequence that can not be found. (#83)
  • TileMapLayers have been seperated into Orthogonal and Isometric classes to keep code more maintainable as well as more succinct. (#85)
  • Additional file management methods added to the FileStore class. (#103)
  • You can now pass parameters to a states preload method when switching states. (#104)
  • You can now filter out messages to be logged out when using the Kiwi.Log. (#151)
  • Much better consistency for passing file types. (#156)
  • @rydairegames added a method to get a tile when you know its index. (#160)
  • ArcadePhysics now contains a rotateToVelocity method. (#179)
  • Clocks now contains deltas. (#183)
  • You can now assign floating point values when changing an Animation‘s frame; they will be rounded to the nearest frame. (#186)
  • Audio now contains an onComplete signal. (#189)
  • Context menu events have been added to the Mouse Input Manager. (#191)
  • HUDWidgets can change the origin the position is based on. (#193)
  • New get children by tag methods added to groups. (#195)

Bug Fixes

  • Animation employs more rigorous methods which ensure the frameIndex is correct. (#184)
  • Timer no longer hangs when the interval is set to 0ms. (#187)
  • setInterval and setTimeout now deal with clock units. (#188)
  • IconBar positioning fixed. (#192)
  • Minor fix with the image loading when using the xhr + arraybuffer methods of loading.
  • ArcadePhysics tile collision boxes made smaller to give better collisions.

Special thanks goes out to @rydairegames for providing the getTileFromIndex method. We think it is extremely useful already.

More details can be found on the Kiwi.JS repo under the 1.3.0 milestone.

If you have any questions, or would like to report a bug, please resist the urge to shout, “Curse you, Moriarty!” Instead, visit our website and make use of our growing community!

]]> 0
Kiwi Examples are Live! Tue, 17 Feb 2015 23:13:47 +0000 We have heard your pleas for a better Kiwi.js examples webpage and we are pleased to announce that it is finally here!

If you ever thought your game needed a little more pizzazz or you simply could not figure out how to do that one tricky thing then our new examples page might be just the thing you’ve been looking for.

The examples webpage covers everything from the Animation component to Tweens and we are not stopping there. We plan to update this examples webpage with all of the features that Kiwi.js has to offer and everything that it will offer in the future. So check in regularly to ensure that you keep getting the most out of Kiwi.js.



]]> 0
KiwiJS v1.2.0 – Kiwi.Log Debug System Mon, 16 Feb 2015 22:00:10 +0000 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:

var kl = Kiwi.Log;

// Example use
kl.log( "alias created", "#alias")

Basic Output

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


Kiwi.Log.log( "This is a log" );

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.


Kiwi.Log.warn( "This is a warning" );

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.


Kiwi.Log.error( "This is an error" );

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 concatenate multiple strings"
Kiwi.Log.log( "You can concatenate", "multiple strings" );

// "You can also output object properties such as 100"
var point = new Kiwi.Geom.Point( 100, 200 );
Kiwi.Log.warn( "You can also output object properties such as", point.x );

// "Or entire objects such as", Kiwi.Point { x: 100, y: 200 }
Kiwi.Log.error( "Or entire objects such as", point );

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.

Kiwi.Log.log( "This message has tags", "#tag", "#example" )

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.

// Populate the log
Kiwi.Log.log( "The sky is blue", "#color" );
Kiwi.Log.log( "The sky is angry", "#emotion" );

// Returns "The sky is blue #color"
Kiwi.Log.showAll( "#color" );

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.

]]> 0
KiwiJS v1.2.3 Available Mon, 16 Feb 2015 21:55:49 +0000 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!

]]> 0
KiwiJS v1.2.0 – Color Object Wed, 11 Feb 2015 22:00:13 +0000 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:

// Default color (medium gray)
var color1 = new Kiwi.Utils.Color();

// Specific color
var color2 = new Kiwi.Utils.Color( 1, 0.5, 0.25, 1 );

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

// Set colors
color.set( 0.25, 0.5, 1, 0.5 );

// Set individual channels to the same result
color.r = 0.25;
color.g = 0.5;
color.b = 1;
color.a = 0.5

// You do not have to specify an alpha property:
color.set( 1, 0, 0 );

You may access colors on the object as follows:

Kiwi.Log.log( color.r, color.g, color.b, color.a );

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:

// Old black
text.color = "#000000";

// New black
text.color = "000";
text.color = "0x000000ff";
text.color = [ 0, 0, 0 ];
text.color = [ 1, 1, 0, "hsv" ];

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!

]]> 0
KiwiJS v1.2.0 – Improved Clocks and Time Mon, 09 Feb 2015 22:00:13 +0000 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.

// Run from a State.create method
var worldClock = "world" );
var uiClock = "ui" );

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.

// Example of rate in use
// This assumes an Entity, which always has an onboard clock
this.transform.rotation += 0.01 * this.clock.rate;


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.

// During state create

// Set the game to treat skips as 0.5 seconds at most = 500;


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:

var clock =;
var timer = clock.createTimer( "timeoutTimer", 1 );
timer.createTimerEvent( TimerEvent.TIMER_STOP,
    function() {

        // The only bit we care about
        console.log( "Time's Up" );

        // Clean up the elapsed timer
        clock.removeTimer( timer );
    } );

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:

var func = function() {
    console.log( "Time's Up" );
var timer = func, 1000 );

Much nicer.

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

setTimeout( callback, timeout, context, ...args )

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.

var func = function() {
    console.log( "...time loop. Help, I'm stuck in a..." );
var timer = func, 1000 );

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: timer );

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:

// Within a State.create method...

var clocks = {}; = "world" );
clocks.ui = "ui" );
var tweens = {}; = new Kiwi.Animations.Tweens.TweenManager(, );
tweens.ui = new Kiwi.Animations.Tweens.TweenManager(, clocks.ui );

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.

// Create a tween on mySprite
var tween = mySprite );

// Configure the tween
var destination = {
    rotation: Math.PI,
    x: 100,
    y: 200
var duration = 1000;
var tweenType = Kiwi.Animations.Tweens.Easing.Linear.None; destination, duration, tweenType );

// You may also start the Tween automatically by adding "true"
// to the end of its parameters. destination, duration, tweenType, true );

// No need to call "start"

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.

// Best practice per-frame iteration
this.rotation += 0.01 * this.clock.rate;

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.

// Pause a clock

// Alternate pause method
clock.timeScale = 0;

// Resume a clock

// Or if using alternate method
clock.timeScale = 1;

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.

]]> 0
KiwiJS v1.2.2 Ready To Roll Mon, 09 Feb 2015 21:45:33 +0000 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.
]]> 0
KiwiJS v1.2.0 – Entity Component System Wed, 04 Feb 2015 22:00:11 +0000 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:

// Suppose there exists a Sprite, "mySprite"

// Create component
var component = new Kiwi.Component( mySprite, "myComponentName" );

// Add component
mySprite.components.add( component );

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.

// Define function
var myFunction = function() {

    // It's always a good idea to call super,
    // even if you don't expect it to do anything. this );

    // This function will smoothly rotate an entity
    this.owner.rotation += 0.01 * this.owner.clock.rate;

// Add function to component
component.update = myFunction;

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.

// Remove by object
mySprite.components.removeComponent( component );

// Remove by name
mySprite.components.removeComponentByName( "myComponent" );

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.

component.update = function() {

component.postUpdate = function() {

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.

// Custom component template for KiwiJS

var CustomComponent = function( params ) {

    // We recommend using a "params" object, as you can pass
    // any number of optional parameters in any order
    // as properties of the "params" object.

    // Call super with "owner" and "name" in params this, params.owner, );

    // Assign custom parameters here
Kiwi.extend( CustomComponent, Kiwi.Component );

CustomComponent.prototype.objType = function() {
    return "CustomComponent";

CustomComponent.prototype.preUpdate = function() {
    // Your custom preUpdate code here

CustomComponent.prototype.update = function() {
    // Your custom update code here

CustomComponent.prototype.postUpdate = function() {
    // Your custom postUpdate code here

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!

]]> 4