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!

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

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

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

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

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

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

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

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

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

Coming Soon: KiwiJS v1.2.0

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

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

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

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

Watch this space.

Grit your teeth – Damage Pipeline Plugin incoming

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

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

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

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

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

March of the Plugins

Today we’re rolling out a veritable cavalcade of fixes and updates for out plugin ecosystem. This covers the WebGL Particles, Primitives, Particle Pack 1, and Particle Pack 2 plugins.

The WebGL Particles Plugin updates to v1.1.2. This release fixes a long-standing bug which caused particles to be offset. They now appear in the correct location. v1.1.2 also fixes a bug where you couldn’t change certain properties if the particle object was the only object in a scene. You are unlikely to have a game with a solo particle object, but you are very likely to have a development project in this state, so this was an important fix.

The Primitives Plugin updates to v1.0.1. This release enables input on primitives; you may now click on them (as defined by the bounding box). v1.0.1 also fixes a bug whereby certain properties when set to 0 would not be correctly interpreted.

Particle Pack 1 and Particle Pack 2 have been updated to v1.0.2 and v1.0.3 respectively. This release updates the packs to WebGL Particles Plugin v1.1.2, which correctly offsets particles.

There are plenty of exciting releases just around the corner. For example, the long-awaited particle effect editor is nearly ready. More on this as it develops!

HTML5 Gamepad plugin!

Hey guys! If you’ve ever wanted to use your Gamepad in your html5 games you do not have to wait any longer!

The HTML5 Gamepad-Plugin for Kiwijs does just that. It allows you to easily connect up to 4 Gamepads to one html5 game.

Now you will finally be able to make those games you always dreamed of. So go ahead and grab a copy of the plugin from our repository and get coding!

Links

Gamepad-plugin for Kiwijs

Rigid Body Physics System

Physics! A fantastic and awfully complex feature which a lot of games use. And it’s just been made easier in Kiwi.

Today we are happy to announce the ChipmunkPhysics Plugin for KiwiJS. This latest plugin brings the processes of Chipmunk and Kiwi together, allowing you to create games which use the Chipmunk2D rigid body physics library.

Thanks to the fabulous people of Chipmunk2D and those who made a JavaScript port of it. Without them this plugin would not be possible.

Break-apart Kiwi: Example

  • Toggle the debug overlay with the button in the top left corner.
  • Click and drag a shape to move it.
  • Click on empty space in the center of the game to apply gravity.

You can obtain a copy of the plugin from Github. Further information can be found in the tutorial section.

We plan to add more features to this plugin in the future, such as Tilemap support, the possibilities of defining shapes in the Texture Atlas, and more as we think of them. So get in contact if you come up with a idea or would like to help out!

Let us know what you think!

WebGL Particle Plugin updated to 1.1.1

Announcing version 1.1.1 of the WebGL Particle Plugin, your passport to super fast particle effects. This version brings several important bugfixes, including better WebGL stability and full CocoonJS compatibility. We’ve also tightened up the performance under the hood.

Get the new plugin now from Github.

While you’re at it, check out our awesome cartoon particle pack and muzzle flash particle pack, available for purchase now. We’ll have them updated to the latest technology in the next 24 hours.