Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
13. May 2016

 

One of the challenges with prototyping games is finding assets to work with.  Simple boxes are fine, but if you are working on a game with animations this proves a bit more challenging.  Therefore I created a simple sequence of spritesheets you can use in your game.   The package includes an idle, walk cycle, jump up and forward, death and duck animations.  This animation shows all of the various frames of animation.  The character was created using Fuse then animated using Mixamo and finally exported to sprite sheets using TexturePacker.

gifanimation

 

There are several different options here. 

 

Raw Sprites

( Download Link 18MB )

These are all of the raw sprites as individual files, each sprite is 512x512 pixels in size.

 

Phaser Sprite Sheets

( Download Link 13MB )

This is a set of sprite atlases and a JSON Array format for consuming in the Phaser game engine.  (See below for code)

 

Generic Sprite Sheets

( Download Link 14MB )

This is simply all of the frames of animation across several separate images, usable in any game engine.

 

License

CC0 icon These files are released under the Creative Commons CC0 license.  Basically do what you will, how you will, when you will, with whomever you will.  I on the other hand assume no responsibility for anything that may happen as a result.

 

Using In Code

The following is a example of using the generated spritesheet in Phaser, a popular HTML5 game library.  The entire project is available here as a zip.  If you are interested in learning more about Phaser I have a complete tutorial series available here.

function Game() {}

var character;

Game.prototype.preload = function () {
    this.game.load.atlas('walkSS','assets/walk.png','assets/walk.json', Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
    this.game.load.atlas('dieSS','assets/die.png','assets/die.json', Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
    this.game.load.atlas('idleSS','assets/idle.png','assets/idle.json', Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
    this.game.load.atlas('jumpForwardSS','assets/jumpForward.png','assets/jumpForward.json', Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
    this.game.load.atlas('jumpUpSS','assets/jumpUp.png','assets/jumpUp.json', Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
    this.game.load.atlas('rollSS','assets/roll.png','assets/roll.json', Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
};

Game.prototype.create = function () {
  this.input.onDown.add(this.onInputDown, this);
    character = this.game.add.sprite(0,0,'idleSS',0);
    character.animations.add("idle");
    character.animations.play("idle",30,true);
};

Game.prototype.update = function () {};

Game.prototype.onInputDown = function () {
};

module.exports = Game;

 

All of the binaries used to generate this project, including the FBX animations, a fully configured Blend file, etc. are available for download by Patreon backers.  Simply log in to your Patreon account for the download link and password.

Art


5. May 2016

 

Introduction

Welcome to the first part of a multipart tutorial series on creating games using the Haxe programming language with the Heaps graphics engine.  Heaps is under development by Nicolas Cannasse, the guy that created the Haxe language in the first place.  In his own words:

Heaps is a cross platform graphics engine designed for high performance games. It's designed to leverage modern GPUs that are commonly available on both desktop and mobile devices. The framework currently supports HTML5 WebGL, Flash Stage3D, native Mobile (iOS and Android) and Desktop with OpenGL. 

Heaps is a very cool library, but not an incredibly well documented one.  So that’s where this tutorial series comes in.  We are going to look at creating 2D then 3D graphics using the Heaps engine.  For this series I will be doing both text and video versions of each tutorial.  The video version of this tutorial is available here.

 

Setting Up Your Haxe Development Environment

This tutorial is going to assume you are using Windows, if you are on another operating system, the steps are going to vary slightly.

First head to Haxe.org/download and download the appropriate Haxe installer for the most reason version.

image 

In my case I am going with the Windows Installer.  Run the executable and say yes to any security messages you receive.  You want to install everything like so:

image

 

Install where ever you like:

image

 

Verify your install worked correctly.  Fire up a command prompt and type haxelib version:

image

 

That was easy, eh?  Next you will probably want an IDE or Editor.  Personally I am using Haxe Develop, a special port of Flash Develop.  This is a Windows only IDE though.  Another option is Visual Studio Code with the Haxe language extensions.

 

Finally we need to install the Heaps library.  It’s not registered with Haxelib yet, so we currently have to install it from Github.  Run the command:

 

haxelib git heaps https://github.com/ncannasse/heaps.git

image

 

And done.

 

Creating a Hello World application

Now let’s create our first application to make sure everything is up and running correctly.  A simple hello world app.

Assuming you are using HaxeDevelop, go ahead and create a new project via Project->New Project

image

 

I created a JavaScript project like:

image

 

Inside our project folder, we need to create a folder for our resources.  I simply created a directory called res.  Simply right click your project in the Project panel and select Add->New Folder...

image

 

Next we need a TTF file, I personally used this font.  Simply download that zip and copy the ttf file into the newly created res directory.  You can open an Explorer window to that directory by right clicking it and selecting Explore.  I personally renamed it to not be all caps, it should work either way though.  If you are using HaxeDevelop, your project should look something like this:

image

 

We have two final bits of configuration.  First we need to text HaxeDevelop that we use the Heaps library, and that the resource folder is named Res.  Right click your project and select Properties

image

 

Next select the Compiler Options tab.  First add an entry to Compiler options with the value –D resourcePath=”res”.  Then add a value to Libraries of heaps.  That’s it, click Apply then Ok.

image

 

Finally some code!  First we need a WebGL canvas for our application to run in.  Simply open up index.html located in the Bin folder and add a canvas.  Your code should look something like:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8"/>
	<title>JSTest</title>
	<meta name="description" content="" />
</head>
<body>
	<canvas id="webgl" style="width:100%;height:100%"></canvas>
	<script src="JSTest.js"></script>
</body>
</html>

 

Now we need to edit our main Haxe code.  By default it will be called Main.hx and it’s the entry point (and entirety) of our program.  Enter the following code:

import h2d.Text;
import hxd.Res;
import hxd.res.Font;
import js.Lib;

class Main extends hxd.App {
        var text : Text;

		// Called on creation
        override function init() {
			// Initialize all loaders for embeded resources
			Res.initEmbed();
			// Create an instance of wireframe.tff located in our res folder, then create a font2d of 128pt size
			var font = Res.wireframe.build(128);
			// Create a new text object using the newly created font, parented to the 2d scene
            text = new Text(font, s2d);
			// Assign the text
			text.text = "Hello World";
			// Make it read, using hex code ( RR GG BB, each two hex characters represent an RGB value from 0 - 255 )
			text.textColor = 0xFF0000;
        }

		// Called each frame
        override function update(dt:Float) {
			// simply scale our text object up until it's 3x normal size, repeat forever
			var scaleAmount = 0.01;
			if (text.scaleX < 3.0) text.setScale(text.scaleX + scaleAmount);
			else text.setScale(1);
			
        }

        static function main() {
            new Main();
        }
    }

Now go ahead and run your code by either hitting F5 or click this button image

You should see:

GIF

 

Congratulations, your first Haxe programming using the Heaps library.  Next up, we will jump into 2D graphics with Heaps.

 

Video

Programming


29. April 2016

 

TexturePacker is a handy tool I’ve featured several times here on GameFromScratch as well as a video feature as part of the gamedev toolbox series.  It’s one of those handy Swiss army style tools that enables you to pack multiple images into one or more sprite sheets.  Texture Packer 4.2 brings a number of new features to the table:

  • a simplified user interface is available now for new users
  • improved help
  • indexed PNG (PNG-8) (more) available
  • improved sprite sheet animation previewer

Sprite sheet animation previewer

  • support for ETC2, PVRTCII, DXT1/5 formats
  • user interface cleanup
  • several fixes
    • all data formats now use UTF-8
    • EaselJS/CreateJS animation frames now written correctly
    • now case sensitive aware on MacOS
    • better Cocos2d-x support

GameDev News


25. April 2016

 

One of the major advantages to working in 3D is once you have your character modeled and rigged, creating new animations is simply a matter of defining a series of poses on a timeline.  Animations are generally defined by moving a series of bones controlling your mesh, which in turn are powered by a system called inverse kinematics.  IK is basically a fancy way of saying “move an end bone and the computer will calculate how all the other bones in the chain will respond” enabling you to animate by positioning the foot forimage example and the ankle, knee and hip will rotate appropriately.  It’s a pretty powerful way to perform animation and every single major 3D application implements IK (and FK – forward kinematics).

 

In the land of 2D art, the process is often quite different.  Generally the approach here is to generate a sprite sheet, which is a sequence of slightly altered versions of the same character, which played in sequence results in an animation.  If you ever done a flipbook animation at the top corner of any of your textbooks, you already have the process of traditional 2D animation down.  There are other techniques such as onion skinning and rotoscoping to aid in the animation process, but it still remains time intensive.  If only there was some way to take the 3D worlds bone based animations and apply them to generating 2D art?  Well, there is... Spine.

 

Today we are going to look inside Spine, look at the art generation process, how to make sprite graphics that are animation ready, define an animation, then perhaps most importantly, play that animation back in our game engine of choice.  Since Spine itself is built over top of the LibGDX library (by one of the frameworks founders to boot), therefore I suppose a LibGDX example makes the most sense.  If you are bored, the story of how Spine came to be is an interesting read.

 

Full disclosure, I requested a review license in order to get hands on time with Spine.  Additionally some of the assets I am using in this demonstration are part of asset packs available for purchase and aren’t my creation.  Spine is commercial software, ranging in price from $70 for the essentials version, $300 for professional and $2200 for enterprise (which is tied to your companies revenue).  There is a free trial available and capable of doing everything we are about to do below except export and run in code.  Without further ado, let’s jump in.  As is often the case on GameFromScratch, if you prefer a video version one is available here as well as embedded below.

 

Meet Spine

Here is the main Spine interface:

image

 

It’s actually an exercise in simplicity which I appreciate.  It also supports UI scaling, so works well on high DPI displays, something far too many applications suck at, so I also appreciate that.  The left hand viewport is where the magic happens, this is where you compose your characters and animations, while on the right hand side you’ve got your project hierarchy a scene graph of sorts.  The primary UI is across the bottom of the screen.  You can easily pan and zoom around the display using a combination or RMB and Ctrl + RMB.  There is some additional complexity hidden away behind this menu:

image

 

But most of the time, what you see is actually all that you need.  It’s a very clean and simple UI.  Notice in the top left corner it says SETUP.  This is because you are currently in Setup mode.  Once our Sprite has been assembled and our bones have been arranged ( more on this in a moment ), we can then switch in to animation mode by clicking SETUP.

image

In animation mode, its all about posing our character.  Notice SETUP changes to ANIMATE and our interface changes slightly.  Now we have a timeline across the bottom of the screen.  We will get back to that in a moment.

 

Creating Spine Ready Sprites

Creating a sprite that is ready to be animated in Spine is pretty close to traditional sprite based animation with two major exceptions.  First, you cut your image up into several different pieces.  You can draw your sprite as a single image if you wish, but once you are done you need to cut it into several different animatable pieces.  Consider the sprite from the above screenshots:

image

This looks like a single drawn sprite, but it’s actually made up for several pieces arranged together.  If you look in the images section of the hierarchy, you can see it’s actually composed of several different images:

image

 

Again, you can draw your sprite how you normally would, but each animatable piece will need to be cut up to proceed in Spine.  This leads to our second requirement...  you also need to draw parts of the images that are normally obscured.  Again, using this example, even if the upper arm isn’t full shown due to being obscured by the body you still need to draw the entire arm, as the visibility can change as the sprite moves, for example:

imageimage

 

So when drawing the pieces of your sprite, you have to think about the depth as well.  Here for example are all the pieces that go together to make this character:

image

 

Rigging Your Character

Next up comes perhaps the most time intensive portion of working with Spine, rigging you character.  You can think of this as arranging all the various images together to create your character, while defining the underlying armature (fancy word for skeleton).  We will do a very simple skeleton, just to demonstrate the process.  You will notice in the tree view that there is a root node under our skeleton:

image

 

This is the very base of the skeleton and all bones are parented to it ultimately.  From here we need to create a root bone, it’s very common to start from the hips, which is what we will do.  Using the create tool, we will quickly create a simple leg skeleton:

image

Click once to set the start of the skeleton, then move the mouse and click again to set the first bone.  Now move down slightly and set another bone, like so:

image

In the hierarchy I rename the bones to values that make sense.

image

Now that we have bones, let’s attach some images to each.  From the images section you can simply drag the appropriate image onto the bone, like so:

image

You will be prompted if you want to go ahead with it:

image

 

The image is now parented to that bone.  By selecting the image you can now transform, rotate and resize it so it best matches the underlying bone:

image

You can also modifying the bone length by hovering over the tip, like so:

GIF

 

Now repeat for the lower bone, like so:

image

 

You end up with a hierarchy like:

image

 

Extremely simple, but the character is rigged, well, the leg is anyways.

 

Creating an Animation

 

Now that we have a very simple animatable character, let’s now switch over to ANIMATE mode.  In the tree view, you should see a section called Animations.  There may be a default one there, otherwise create one using the New Animation button that appears when animation is selected:

image

image

 

Keyframed animation is pretty simple in concept.  You will notice at the bottom of the screen there is now a Dopesheet view:

image

 

Your animation is composed of a set of “key” frames.  That is, you post your character and take a snapshot of the location/rotation/scale of a given bone, then advance the timeline to a different value and repeat the process.  The computer then interpolates between keyframes to create a smooth animation.  You can turn “autokey” on, so that any changes you make in the editing window automatically set a key.  Otherwise you can manually create the key by clicking the green key to the right of each transform:

image

 

Set a key for the default rotate, translate and scale values, or use Autokey.  Next advance the timeline to say 5, like so:

image

 

Next using rotations, manipulate each bone, like so:

gif2

 

Advance the timeline slightly more, then repeat the process all over again.  You can control the playback of your animation using these simple VCR style controls:

image

 

Here is a very simple and crude kicking animation:

gif3

 

Another cool thing you can do is add Events as part of your timeline, like so:

image

image

Enabling you to create events that can be fired in code, allowing you to incorporate programmatic aspects into your animations, such as playing a footstep audio effect.  We will see this process shortly.

 

Exporting the Animation

Now that we’ve got an animation to use in our game, it’s time to export it.  Here there are a couple of choices. 

image

 

You can export your results as a video, a sequence of images or as data.  If you chose to export as an image you can actually have some rather advanced controls, including generating a texture atlas (directly usable in LibGDX) or sprite sheet:

image

 

With results like:

skeleton-kick

 

This approach can be utilized in just about every single kind of game engine available today.  However, where Spine shines is when you chose to export as data instead.  This is where runtimes come in.  These are essentially libraries or code for the various game engines that enable you to use spine format natively.  Full source is available on github and runtimes exist for most 2D engines available including Unity, LibGDX, Love, MonoGame, Torque2D, Cocos2d-x and many more.  In this example I will be using LibGDX.

 

In this case I’m going to export to JSON and generate a texture atlas using the following settings:

image

 

Now let’s break out some code.

 

Using Spine In Game

As mentioned earlier Spine have several runtimes available on github.  In the case of the LibGDX project, you simply have to copy the code into your appropriate source code folder.  Assuming you created a project using the setup utility, this means copying the contents of esotericsoftware to your core\src\com directory.  Then I wrote the following code, adapted from one of their LibGDX examples.

Make sure that you’ve exported your assets and created the atlas in your working directory, most likely \core\assets.  Then use the following code:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.esotericsoftware.spine.*;

public class Spine2 extends ApplicationAdapter {
    private OrthographicCamera camera;
    private SpriteBatch batch;
    private SkeletonRenderer renderer;
    private TextureAtlas atlas;
    private Skeleton skeleton;
    private AnimationState state;

	public void create () {
		camera = new OrthographicCamera();
        camera.setToOrtho(false);
		batch = new SpriteBatch();
		renderer = new SkeletonRenderer();
		renderer.setPremultipliedAlpha(true); // PMA results in correct blending without outlines.

		atlas = new TextureAtlas(Gdx.files.internal("skeleton.atlas"));
		SkeletonJson json = new SkeletonJson(atlas);
		SkeletonData skeletonData = json.readSkeletonData(Gdx.files.internal("skeleton.json"));
		skeleton = new Skeleton(skeletonData);
		skeleton.setPosition(0, 0);

		AnimationStateData stateData = new AnimationStateData(skeletonData);
		state = new AnimationState(stateData);

        // Set up an animation listener so we can respond to custom events or completion
        final AnimationState.TrackEntry track = state.setAnimation(0, "kick", false);
        track.setListener(new AnimationState.AnimationStateListener() {
            @Override
            public void event(int trackIndex, Event event) {
                // Check for the "half" event we defined in the editor
                if(event.getString().equals("half"))
                    System.out.println("Half way baby");
            }

            @Override
            public void complete(int trackIndex, int loopCount) {
                // or the complete event (not END!) when done, fire the idle animation instead
                state.setAnimation(0,"idle",false);
            }

            @Override
            public void start(int trackIndex) {
            }

            @Override
            public void end(int trackIndex) {
            }
        });
	}

	public void render () {
		state.update(Gdx.graphics.getDeltaTime()); // Update the animation time.
		state.apply(skeleton);
		skeleton.updateWorldTransform();

        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
		camera.update();
		batch.getProjectionMatrix().set(camera.combined);
		batch.begin();
		renderer.draw(batch, skeleton);
		batch.end();
	}

	public void dispose () {
		atlas.dispose();
	}
}

 

When you run this code...

gif4

 

In the above code example you can see how you can handle an event you defined in Spine.  Otherwise it’s pretty simply to load and play animations on a character developed in Spine.  There is a comprehensive API, I’ve only touched on a very small part of it here due to space (this is already pretty long...).  There are also several features I never got to mention such as free form deformation ( useful for shapes such as capes ), swappable skins, place able props, etc..  If you are doing 2D animation, Spine is certainly a product you should check it.  Spine is by no means the only option when it comes to 2D animation in games, Spriter and Creature are two other popular alternatives.  It is however a very good option.

 

The Video

Art Programming


4. April 2016

 

Torque2D, an open source (MIT) 2D game engine build on top of Torque 3D technology, just released version 3.3.  This release adds two major new features, positional audio and TextSprite.

From the release notes:

Positional Audiot2d

Simon already put together an in-depth blog post on the virtues of positional audio. You can find it here. Let me give you the highlights. First, one scene can act as a listener. Then any object in that scene can call %object.playSound("beepAssetID") to play that sound. Those sounds can take an optional second parameter which is an AudioDescription. The AudioDescription can specify if the sound should loop along with a few handy other features. These were previously available in older versions of the engine so I image many of you will get the hang of them quickly.
Of course the whole point of all this is to hear the sound in the position it is on the screen. The best part is that the Doppler Effect happens. So you can make things quiz past your characters without any extra work. Again see Simon's blog for more details.

TextSprite

My contribution was the TextSprite. The previous bitmap font sprite, called the ImageFont, has been removed, but I tried to keep the TextSprite as similar as possible to keep updating your projects simple. The TextSprite is far more powerful than the ImageFont and I don't think you'll want to look back once you start using it.

FontAsset

It all starts with a FontAsset which is a new asset that basically takes a Bitmap Font File as its main parameter. This is the file generated directly by AngelCode's Bitmap Font Generator. In fact, the ToyAssets module includes a configuration file with a few example fonts to make it super easy to use. Basically to add a new font you just save the file using the Font Generator and then make a FontAsset taml file with the asset name and a reference to a font file. And just like that, you've got a new font that you can use in your game. The documentation is in the Github T2D Wiki if you want to learn more.

Features

The TextSprite is loaded with cool features so I'll type fast. First, you give your TextSprite a valid FontAsset. Unlike the ImageFont, you can set the size of the TextSprite and think of its bounding box as a box to type in. Inside the box you can align the text to the left, right, center, and justify. You can also vertically align the text to the top, middle, or bottom. When it hits the edges of the box you can set the overflow options. Horizontally, this includes the ability to word-wrap the text, which was a major missing feature of the ImageFont. But you can also shrink the text to fit, clip the text, or just let it overflow the box. Vertically you have similar options sans the wrap.
The font has a font size that applies to every character, but you can further customize the size by scaling the font in the x or y direction. On the font level you can also set the kerning (that's font lingo for space between characters). And finally, since this is a sprite you can set the blend color, rotation, and do things like collisions. You can even grow the sprite which will dynamically change the word-wrapping over time. We could stop here and you'd be happy, but it gets better.

Super Cool Features

You might want to sit down for this. You can change the blend color, scale, and position of individual characters. That means that you can have all white text and put that critical word in blue. You can make the letters shake for a cold character. You could have the text appear one letter at a time as a dialog box as seen in nearly every game. All this and more is now possible with the TextSprite. A new TextSprite Toy has been added to the Sandbox that demonstrates some of these tricks. Take a look at it and then give it a try.

GameDev News


GFS On YouTube

See More Tutorials on DevGa.me!

Month List