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.

Pitfalls

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.

GameDash2D

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.

Favourites

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!

Greetings from Kiwi.JS v1.3.0 “Moriarty”

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!

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.

Aliases

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

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

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

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( Date.now() - 10000, Date.now() - 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.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).
  • color.red, .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 color.red (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.

RGBA Set

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?

HSVA/HSLA Formats

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 }

HSVA/HSLA Set

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").

CSS Set

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 this.game.time.clock.pause().

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.

rate

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.

maxFrameDuration

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.

elapsed()

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.

timeScale

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.

setTimeout()

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.

setInterval()

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.

Animation

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.)

Timer

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 Kiwi.State.prototype.update.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!

KiwiJS v1.2.0 – Refreshed File Loading System

Hello there! Today we are going to have a little look into the file system since it has been refactored in KiwiJS v1.2.0.

Adding Files to the Loader

Adding assets to your games is a fundamental part of the library! We worked on quite a few projects with Kiwi, and after a while we found that we just could never remember the correct order to pass arguments to the add assets methods such as addImage and addSpriteSheet.

We thought that passing a params object would fit the bill. Just have a look at the example below!

Now the addImage method is a bit easy to remember. But have a look at the example below which shows us how it works with the addSpriteSheet method.

Global Files

Whilst adding the new params object we though it would be the perfect the time to expand upon the Global vs. Local asset management concept we currently have in the engine.

Currently each add method contains an argument named “storeAsGlobal”. This is a boolean. When true the asset added will never be deleted by Kiwi runtime itself. You can of course manually remove it. But when it is false that asset will be removed when the runtime switches to another State.

When using the new params object, instead of marking assets as “global”, you will have to set the LAST State the asset is to be used on. The asset will be usable on every State until the State you specify is loaded and then switched off.

Tagging

Now while this isn’t a new feature to Kiwi (we have actually had this for quite some time), we thought we would show you how you can tag assets in Kiwi.

The first step is to tag the asset when creating it. You can also use the addTag method on the Files.

Now once you have tagged a few assets you can remove them, or access them via the FileStore.

Percent Loaded

Default Behaviour

Just loading in your assets will probably not be enough in your games. You may also want to show progress bars.

In Kiwi the percentage loaded can be calculated in two different ways depending on your needs. Regardless of the method it is always a number between 0 and 100.

The first behaviour in Kiwi returns a percentage based on assetsLoaded / numberOfAssetsToLoad. This is the default behaviour in Kiwi.

This is generally perfectly fine behaviour for majority of games, but it does not take into account the size of the files.

Calculating Sizes

The second behaviour returns the percentage based on the numberOfBytesLoaded / numberOfBytesToLoad. This behaviour is disabled by default. In order to calculate the size each file makes a XHR head request asking for the file details, and this has a performance overhead.

Although loading times maybe increased, this is offset by the fact that the number of bytes for the files will be calculated and each file will know how large it is.

Parallel Asset Loading

Currently files are loaded in one after another in a queued fashion. File loading like this is common and in place for a number of reasons but unfortunately it can lead to long loading times.

In KiwiJS 1.2.0 we are happy to introduce the parallel loading feature which can really help!

When this feature is enabled, Files will attempt to load at the same time. This requires browser support, but should work fine with standard images.

The theory is that browsers are already great at managing loading of images and such, so why not let them do what they already do?

So give this feature a try and let us know how it goes!

Thanks for reading!

We hope you find the new features useful – and powerful. It might make a world of difference when loading your games!

Next time: the Entity Component System automates game tasks.

Hello from Kiwi.JS v1.2.0 “Williams”

Happy New Year from the Kiwi team! Today we are happy to release version 1.2.0 of Kiwi.JS, “Williams”.

This version of Kiwi.JS brings powerful new ways to build and automate game architecture. With a robust Entity Component System, more time controls, faster file loading options, a new debug logging system, unified color format, and more, we reckon you’ll be able to build some seriously pro games.

“Williams” is named in honor of Roberta Williams, creator of the King’s Quest series and one of the great adventure game designers. Where would modern gaming be without Williams? We’re big fans here.

You can download 1.2.0 of Kiwi.JS on github now.

New Features

Kiwi.JS v1.2.0 has several exciting new features. Some of these are so cool that we’ll be doing entire posts on them in the near future. Upcoming articles include:

  • Entity Component System
  • Robust Clocks and Better Animation
  • Kiwi.Log Debug System
  • Color System
  • Revised File Loading System

We’ve also made some smaller improvements that don’t merit their own article. We’ll explain those here.

Animation.onComplete

When an Animation is set to a single repetition, and it successfully completes that repetition, it fires a Signal called onComplete. This is useful for signalling the completion of a single event. It is different from onStop, which may fire upon completion, but will also fire if the Animation is interrupted.

Transform Performance Upgrades

GameObjects must have a Transform to set their position in space. Unfortunately, Transforms use matrix mathematics to do their thing, and this can be costly on low-end CPUs such as those in mobile devices.

We’ve streamlined the Transform process to make it 10-30% faster. In addition, we’ve supplied a couple of useful functions to squeeze even more power out of the Transform.

Transform.ignoreParent

By default, Transform will get a matrix from its parent. This allows the Transform to follow a parent through any transformation, as though it were part of the parent Transform. Set ignoreParent = true to disable this, gaining some performance back. The entity will still be able to transform, but it will not respect any parent transforms. This is useful if your entity is not part of a Group. Note that the State is also a kind of Group, so if your entity is a child of the State, and the State does not transform, ignoreParent = true is a great way to get a little more oomph.

Transform.locked

By default, Transform will update its matrix every frame. Set locked = true to disable this, gaining some performance back. The entity will be locked at its current transform. It will still respect parent transforms. This is useful for objects that don’t change often.

TextField.box

TextField now has a hitbox component. This hitbox is a clever estimate based on expected text dimensions. If you wish to add other components, such as physics or input, the presence of a Box will make it possible.

Game domParent can use CSS Selectors

When specifying the domParent in game options, you can now use CSS Selectors as well as DOM element ids.

Kiwi.Utils.Common.isBetween

Tired of writing long conditionals to figure out whether a number is within bounds? isBetween( x, min, max ) will do the heavy lifting for you. Note that it only returns true if x is genuinely between min and max; if x = min or if x = max, it is not between them and is thus false.

Pointer.pressed, Pointer.released

Pointer (and by extension Finger and MouseCursor) now have pressed and released properties. These are true only on the frame directly after the pointer is pressed or released. This was previously difficult to ascertain if you were creating your own input methods.

Camera.transformPointToScreen

You could already call Camera.transformPoint to transform a Point into world coordinates. With transformPointToScreen, you can go the other way. This will tell you where a Point in world space maps to the screen. This can be useful for ascertaining whether something is on screen, positioning HUD elements over game objects, etc.

Reassign Tween.object

There is now a setter that permits you to reassign Tween.object midway through a Tween. This will immediately stop updating the current object. The new object will inherit the current value of any tweening value. Any tweening value that is not present on the new object will be removed from the Tween. This could be useful for substituting one object for another midway through a Tween, as in a transformation sequence or an entity suffering battle damage.

TextField name

What’s wrong with “Textfield”? It’s not properly camel-cased: it should read “TextField”. We’ve added the correct name as an alias. Old code will still work, but new code may be written in a more pleasing fashion.

Release Notes

v1.2.0 "Williams"

New Features

  • Pro architecture tools out the wazoo
  • All Component objects on a Group or Entity will automatically update when the State updates. This permits a full Entity Component System. (#122)
  • Clock greatly improved (#143)
    • Time can run at any rate, in any direction
    • rate property available on clocks
    • Animation, Tween, and TweenManager use new clock abilities
  • Animation has a Signal called onComplete which fires after finishing (#143)
  • Kiwi.Log added. This replaces and upgrades console.log functionality, with recording, tagging, and selective muting. It’s a big step up for debug! (#117)
  • Kiwi.Utils.Color object can record and output color values in a very wide range of formats, including RGB, RGBA, HSL, HSV, CSS color functions, and normalized or integer values. (#135)
  • File system is more flexible
    • Parallel loading option for lightning-fast downloads
    • Load files with easy-to-use parameters
    • Easily manage state-specific files
  • Transform optimisations (#141)
    • Improved performance
    • Transform may be set lock = true to prevent updates and increase performance
    • Transform may be set ignoreParents = true to save performance with objects whose parents don't update
  • TextField now has a hitbox (#137)
  • Game domParent parameter can now use CSS selectors (#131)
  • Kiwi.Utils.Common.between( x, a, b ) method added. It's much faster to check if something is between two numbers now. (#118)
  • Input.Pointers now has pressed and released getters, allowing you to see if a mouse or finger was pressed or released in the last frame only. (#115)
  • Camera.transformPointToScreen added, allowing you to translate world points to screen coordinates. This is the opposite of Camera.transformPoint. (#112)
  • You may now reassign Tween.object, transferring a Tween from one object to another. (#109)
  • State.loadProgress() can now estimate bytes loaded (#66)
  • Timer Helpers implemented. You can now call Clock.setInterval and Clock.setTimeout, rather than mess around with three or more calls to get the same effect. These helpers run on game clocks, and will respect clock manipulation and pausing. (#44)

Bug Fixes

  • XHR loading works with Nodewebkit where status codes are unavailable (#144)
  • Kiwi.Utils.Common.defaultToString is now in camelCase (#140)
  • TileMapLayer.getOverlappingTiles now works correctly with negative coordinates (#139)
  • Kiwi.Time.Clock.removeTimer works correctly (#138)
  • Audio objects now loop correctly after being paused and resumed (#132)
  • PluginManager now correctly allows requirements that match or exceed requested version number, rather than those that match or precede it. (#130)
  • Game prints the correct error message when no stage was specified, or an incorrect stage was specified. (#129)
  • Mouse events now include button data. (#126)
  • AnimationManager now calls onUpdate after changing cellIndex, ensuring that callbacks have more accurate data regarding cells. (#125)
  • StaticImage.objType() now reports "StaticImage" instead of "Sprite" (#119)
  • Spritesheet texture atlas correctly enumerates number of cells. (#116)
  • Timer resumes where it left off after being paused (#113)
  • File loader now correctly interprets files without extensions in CocoonJS (#106)

Deprecations and Removals

  • Textfield is deprecated in favour of TextField alias (#134)
  • Kiwi.Utils.Common.defaultToString is now in camelCase (#140)

Project Architecture

  • Switched to Typescript 1.4. Run npm update to upgrade your packages.

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