Creating a Basic Kiwi.js Game

Note: This tutorial was written using Sublime Text 2, Javascript, Windows 7 and Google Chrome, and therefore images and source code will be in this format.

In this tutorial we will be learning how to create a simple Kiwi.js game with images, sprites, animations and keyboard input. Shown below is the final game from this tutorial. You can move the character left and right using the A and D keys and also get him to crouch using the S.

Download or view the code for this tutorial in the Kiwi.js example repo here inside of the /tutorials/website_examlpes folder.

Setting Up Your HTML Page

To include the Kiwi.js library in a HTML webpage add this line to the page:

Writing the Javascript File

Create a new javascript file called gettingStarted.js in the same folder as your HTML page. This is where we will write the Kiwi.js game. Include it in the HTML page after including the Kiwi.js library.

The Game Object

The first thing we need to do is create a new Kiwi.Game Object. The game object will be responsible for booting the required managers and handling the game loop. Create a new variable called myGame and use the Kiwi.Game constructor to create a new game. This will initialize all the game variables including cameras, state managers etc. Now we need to define our state which will control what happens in the game. After defining the state we can add it to the game and play it.

The Game State

Our game is going to require one game state which will contain the logic for creating the sprites, animations and controlling updating and input. Create a new variable called myState and use the Kiwi.State constructor to create your new state. Give it a unique name for use later on, preferably the same name as the variable.

Creating functions for the state can be done through the following:

Below is a in depth run down of each function in the game state class explaining how it works.

Preloading the Assets

assetsImage

 

Each state has a preload method which will load in our assets for us. It’s all done under the hood so no need to worry about how it all works. The preload method is called as soon as the state is initialized.

Preloading the assets allows us to grab them out of the texture library and assign them to entities. The preload method is a special state method which will initialize and run the game loader class to load in the specified assets. Here we are adding a sprite sheet and an image. They require a name, which will be used later on, the relative URL of the asset. The sprite sheet also requires a width and height parameters, corresponding to the width and height of each frame in the sprite, 150 and 117 in our case.

The Create Method Part 1 – Creating Entities and Input

The create method is called once the preload method has finished loading our assets in. Therefore it is a good time to create our entities. For this game we will need a StaticImage, for the background image and a Sprite, for the character. Also we should create our key objects at this time.

Creating Kiwi.Entities is simple. To make the background we just need to create a StaticImage GameObject and pass it the correct texture, from the texture library, and a position. For the background we can use 0, 0 to place it in the top left corner. The character is exactly the same, pass through the characterSprite texture and use 350, 330 as the coordinates to place him in a nice location on the background.

We want to be able to control and move our character, therefore we need to set up some key input. Creating keys requires adding the specified keycode to our game’s input keyboard using the addKey method. You can choose to use the A,S,D keys or LEFT, RIGHT, DOWN.

The Create Method Part 2 – Adding Animations

The second part of the create function deals with adding animations to the character and adding the entities to the state.

The character won’t animate until we add animations to it. This is where we give names for each animation and specify which frames of the sprite sheet to use. Setting the timing for all the animations as 0.1 gives us nice smooth animation and we should only set the loop to true for the two moving animations.

We also need to track which way our character is facing so we can play the appropriate animation for when the character is facing right or left. Let’s set this to ‘right’ to start.

Lastly we need to play an animation, the ‘idleright’, and add both GameObjects as children to the state. Adding children to the state will automatically update and render them during the update loop.

The Update Method

Every game loop cycle the game’s state manager will call the update function of any active state. In our case the update function will be responsible for checking keyboard input, moving our character and switching animations. Under the hood, the game will be updating variables, rendering images and working out the animations but we don’t need to worry about any of that.

Firstly we need to call the Kiwi.State update prototype function. This will process and update the game loop for us. We don’t need to worry about what that does, it just makes the game work. Now let’s check whether any of our keys were pressed.

If our character is crouched we don’t want him to be able to move so we should check if the S (or Down) key was pressed first. If its isDown boolean is true then we should change the current animation to the (‘crouch’ + this.facing) using the switchTo method.

Now we should check if the A or D keys were pressed. In the same way as before if they key was pressed we should change the animation, unless it is currently playing, to the (move + this.facing) animation, increment or decrement the characters transform x value (to move him left or right) and set the current facing to the left or right direction.

If no key has been pressed simply change the animation to the idle one.

Switching to the new State

Now that we have defined our state, we need to add our state to the game’s state manager using the addState method. Lastly we switch the current state to our game state using the switchState method to initialize the game and we are done!

Share the joy
Comments 13
  1. Brad Shaver

    I am getting an error on the demo above:

    Uncaught TypeError: Cannot read property ‘addKey’ of undefined

    gettingStarted.js line 23:
    this.leftKey = this.game.input.keyboard.addKey(Kiwi.Input.Keycodes.A);

  2. John Wu

    I found some sprite sheets (with license) on the Internet, and I found that the transparent pixels are taken into account when placing the Sprite on the canvas, detecting collisions and setting/getting transform.x/transform.y etc. Is there anyway that It can ignore the transparent pixels without editing the sprite sheet?

  3. The best and easiest way would be to edit the images directly, but you can change the cell/s (area of a Texture Kiwi will use when rendering) by passing additional parameters when using the ‘addImage’ or ‘addSpriteSheet’ methods.

    Otherwise we don’t have anyway of ignoring the transparent pixels currently.

  4. Pretty cool tutorial! The only somewhat weird thing about it is having sprite sheet frames for both directions, instead of just having all the frames for just the right side and obtaining left side by mirroring the right side frames (aka scaling in X axis by -1).

  5. Hey Dread Knight,

    Yes you can change the direction using the scaleX property of the Sprite and that is usually how we do it here at the Kiwi.js offices!

    When writing this documentation we tried to make it as easy to follow as possible for beginners to Kiwi.js! In later tutorials we start using the scaleX property of the Sprite.

    Thanks for the helpful comment!

  6. Skyler

    I *think* I did everything correctly, but when I open up the index.htm file, I just have a blank white screen.

  7. BenjaminDRichards

    Re: Skyler-
    _
    There are always some speed bumps getting started. A couple of common problems (sorry if these seem really basic, I don’t know your comfort level):
    _
    Do you have any useful messages in the browser console? (This varies between browsers, but look for “tools” or “developer” menu options.) This will usually display errors and give you a direction to start a bug-hunt.
    _
    Are you running your index.htm straight out of the file system? If so, it probably won’t work. For deeply ironic reasons, files on your computer are viewed as a security risk by your browser in a way that files on a server are not. We recommend using WAMP or MAMP to run your own local server. It’s kinda silly, but it’s a vital part of the development workflow.
    _
    Please let us know if this doesn’t work, and we can take a closer look.

  8. trigfox

    Yeah, I was running it directly from my file system. Do you know if there is a way to run a local server off of a chromebook? That’s all I have access to, so I figured this would be a good starting point for making projects.

    I also have Ubuntu installed on here, so if it isn’t possible to run a server on ChromeOS, I can look into running one there.

  9. trigfox

    So I found a good Cloud based IDE called Cloud9. It is able to run the index.htm file in a preview window. The preview window is quite small, though, and for some reason nothing displays when I try to maximize it. Hopefully I can find a way to run it in my own local server, but for now this will allow me to mess around with some of the tutorials and learn the basics.

    PS – I noticed that if you hold down one direction and press the other direction before releasing the first direction, the animation freezes but the character still moves in the second direction.

  10. BenjaminDRichards

    Sounds like you’ve managed to get results, at least. We may have to look into Cloud9 ourselves; it would be good to figure out exactly what’s going on with this “disappears when maximised” thing.

    We don’t have all the testing hardware we’d like, so I can’t officially say anything about working with ChromeOS. I did, however, find this guide: https://medium.com/@samx18/setup-a-complete-local-development-environment-on-your-arm-chromebook-b7fb9c14ec97 It seems to check a lot of the boxes, including LAMP in the WAMP/MAMP vein. I cannot verify its contents or safety, but it’s worth doing some research.

    I’m not getting the directionality issue in my own code. Are you chaining the else-ifs to select just a single input case?

  11. trigfox

    I’m not really sure what was up with the direction issue. It isn’t happening any more. I’ll check out that guide, thanks!

Leave a Reply

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

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