I recently presented a step-by-step workshop titled “Making A 2D Sprite-Based Game With Unity” to the Toronto SkillSwap community which is “A collaborative group for folks interested in sharing their skills and training with other developers in Toronto, and for folks interested in learning!”.
Around 50 people showed up to the 3 hour workshop and although we tried our hardest to get through all of the content, we only completed about 1/2 of the project before it was time to move on to the beer drinking portion of the event.
So while I still had all of the project steps fresh in my mind, I figured it would be a good idea to go through the workshop at home and screencast the whole thing so that everyone could get a chance to follow along with the complete tutorial.
Here’s a look at what the completed project looks like, because you know; editor screenshots in blog posts look cool.
Before you jump into the video, here’s all the stuff you’ll need to complete the project:
If you find our tutorials useful, please considering buying one or more of our games and apps for iPhone and iPad. Your support helps to keep the tutorials flowing!
Giant Moto: High flying arcade style motocross action! Small Space: Fly a spaceship, eat space creatures, get huge, score point! Holeshot Drag Racing: High speed drag racing action! Alien Booth: Transform pictures of your friends into awesome aliens! iSpoof Walken: A hilarious look into the world of Christopher Walken! Gaga Eyes: Transform pictures of your friends to give them huge anime eyes!
About the author
Tim Miller is a veteran game developer with over 15 years experience in the video game industry working as a Level Designer and Lead Level Designer at LucasArts, Secret Level and Nihilistic Software. He co-founded Rocket 5 Studios with his wife Cathy and their dog Rocket in 2009. Twitter, LinkedIn, Portfolio
Animating animals is usually fun, but can often be complicated and technical. Figuring out what to do with all those legs can really trip up an animator. We can animate human-shaped characters a lot easier than multi-legged beasts because we have an intuitive knowledge of the way bipeds move. It is easy for an animator to act out a motion when the character moves like us; feeling the action ‘in the body’ helps us understand how to animate it. So what happens when the character is a quadruped and you don’t have that intuitive feel at your disposal? How do you make that movement believable? Suitable reference and a sophisticated media player is the place to start.
Luckily for the animation community, there is a wealth of reference material that can help. I’ll walk you through my process for animating quadruped locomotion and share classic references that will help you deconstruct the fundamentals of the four gaits: walk, run, trot and gallop. I’ll also share an example of my own 3D walk animation and offer technical tips for creating believable quadruped locomotion cycles.
Click the image to see the animation. Horse Locomotion Walk 30 courtesy of www.rhinohouse.com
With a media viewer that can scrub single-frame backwards and forwards, like Quicktime, you can watch the movement frame by frame. Drawing thumbnail images with directional notes helps you synthesize the information. There are now lots of websites out there that put up live-action animal footage, such as the Rhino House Human and Animal locomotion website, which has a built-in player that can scrub their video reference material (click the image on the right to check out their website and viewer). Thanks to the Internet, finding reference and getting into it to see what is going on is the easy part. The hard part is converting that information into something that makes sense to the animator and for the character that is to be animated.
Following a process speeds up your workflow. Before I get into the creative part of animating, I usually have all of my research done. Gathering and absorbing all of the technical details and reference material beforehand frees me up to get into the creative ‘flow’ of animating, with easy access to my reference material. My process is something like this:
Consider what animal most closely resembles the beast I need to animate?
Search for reference material. Here are the sources I find useful:
Analyze the reference material and find the section of the footage that is most useful.
Create thumbnail drawings to assist with my animation, including notes on direction and any unusual qualities I can see in footage.
The Four Gaits
In the course of my career, I’ve learned that there is a surprising similarity in how quadrupeds move, from species to species. Eadweard Muybridge’s photographic works may be a century old, but they are still relevant and extremely useful. In his introduction to Animal Locomotion, he maintains that most quadrupeds – be they dogs, cats, horses or rhinoceroses – follow the same footfall pattern. This is the order in which the hooves or paws strike the ground while moving through the various gaits. Where they differ is in the flexibility of the spine. Visualize a rhino running, as opposed to a cheetah. The exceptions, according to Muybridge, are elephants and animals like kangaroos.
The four speeds of movement, or the four ‘gaits’, are shared amongst most four-legged animals. Almost every quadruped walks, trots, canters and gallops, and their legs move in the same manner when they do it. As you can see in the image below, adapted from Muybridge’s Animal Locomotion, the gaits have been broken down into symbols illustrating which leg strikes the ground in which order, assuming the animal is facing north with the right legs on the right and the left legs on the left.
For example, with the rotary gallop gait, if you start your cycle with the left rear foot striking the ground first, the next in sequence to hit the ground would be the right rear foot, then the right fore foot, followed by the left fore foot. As for the transverse and rotary gallops, I’ve found the rotary gallop more often in reference material than the transverse, which I’ve mainly seen in horse footage. The canter is the roughest gait, with a lot of up-and-down movement. Elephants don’t seem to follow these rules, and should be considered separately.
Once you get the legs moving roughly in the order that is appropriate, you can be creative with the rest of the body.
To save time, you could animate a ‘vanilla’ gait cycle for each gait with the leg movements blocked in on keys and breakdowns only and the body and head having the rough up-and-down motion laid in on those keys. If using a universal rig, this file could then be exported onto any beast (with minimal adjustments, depending on the disparities of beast shape) and be used as a starting point for the animations. Several different types or speeds of walks could also be created from this base file simply by playing with the amount of frames in the animation and the distance between the legs in the stride position or the distance the beast travels in the ‘leap’ part of the gallop.
In the case of the walk gait, the rear left foot strikes first followed by the left fore leg. The rear right leg strikes third with the right fore leg falling last. The walk is the slowest gait and is shared by all quadrupeds. Muybridge breaks down this information into a chart for the walk, trot, canter and gallop gaits in the introduction of Animal Locomotion. Converted into a graphic table, a walk cycle would look like this:
Horses are great animals to study because their legs are so long and slender, creating a easily legible silhouette. Below is an example of a walk cycle broken down into 8 phases:
Image adapted from Horse Locomotion Walk 01, courtesy of www.rhinohouse.com
Once you understand what the feet are doing, it becomes easier to understand what to animate next. Think of the quadruped walk as two offset human walk cycles. I wonder how often studios have used two people in a horse costume for motion capture? Preston Blair’s iconic walk cycle with the “stride” and “passing” key positions is a great illustration of the basics of a biped walk demonstrating the following: fall into the stride and recover and rise up into the passing position.
Adapted from Preston Blair, Animation, 1948
For the quadruped, the hips and chest become two offset ‘bouncing balls’ in the same manner as the hips in a bipedal walk. Consider circled image 23 from the horse walk cycle (below), which shows the fore legs in the “stride” position and the hind legs in the “passing” position. I’ve added circles to show the up and down motion of the hips and chest in that phase of the movement. The head could then be animated as yet another bouncing ball, offset from the hips and chest (follow-through! overlap!).
Image adapted from Horse Locomotion Walk 01, courtesy of www.rhinohouse.com
Animating A Walk
To illustrate this locomotion in 3-D animation, I’ve roughed in a slow 40-frame walk cycle. Cycles must be symmetrical, or there will be a visible hitch in the walk, like a limp or a hit in the animation.
There are almost as many methods of animating as there are animators, but I prefer to approach posing as I would with 2D or Classical animation. Posing out the whole character, rather than starting with the hips or isolating the lower body, and working on the entire character at once when creating the four major poses. Details like toes and tails can be ignored or turned off at this stage. I create the four major keys or poses of the walk: two stride and two passing. I make them as symmetrical as possible, but they don’t have to be mathematically the same.
There is an advantage to keying all major elements on the same frame. At this point, the keys can be slid around easily to change the timing of the walk. It is quick and easy to adapt and manipulate your cycle by figuring out your basic timing to the point where you start to add finishing details like overlap and follow-through. Keys arranged in an orderly fashion are really easy to manipulate in your 3D software package (here I am using the dope sheet in Maya 2011).
Four key poses, JoJo walk, property of Rocket 5 Studios
This is also the break off point where different kinds of walk cycles can be created now that the feet have been appropriately positioned. Variety can be added like floppy overlap or stealthy sneak. The four basic poses can also be used as a starting point for other walks. You don’t have to re-create the 4 basic key poses; you only have to adapt them to your specific purposes. Use the graph editor or tweak by hand, but remember to have each opposite pose match each other.
It is important that your software has a great graph editor. When animating cycles, I spend a fair amount of time cleaning up the graph to get symmetrical movement. Don’t forget to check all channels! The above video has been carefully tweaked to remove all hits and holds. The stage just prior to this revealed a few errors with the arms:
There are several ways to fix errors like this but the easiest for me at this stage is to look at the graph editor and find out where there is a problem with the curve.
note: flat tangents causing slow down at apex of movement
The highlighted motion trail shows other problems that can be solved by the graph editor, such as the linear movement of the arm in the air. Arcs always look more natural than linear paths of action. The solution for the slowdown in the forward progression of the arm is to fix the curve so that it can cycle smoothly, as seen below.
Grab spline handles and move them so that curve looks like it can cycle or repeat.
The next step is to flesh in the walk, adding overlap and follow-through, offsetting the head and making sure there is enough weight in the up and down movements of the hips and chest. When you are pretty sure the cycle is working the way you want it to, animate the feet, hands, fingers and toes. I usually animate the tail last, one rotational axis at a time.
Walks and Runs: In Brief
Walks and runs can be considered a controlled fall with a little acceleration happening right after the passing position, which is similar to a push-off. As with all movement cycles, the forward or Z-translation would be non-linear.
The speed of the walk is dictated by the length of the legs and how far apart the feet are planted in the stride position. There isn’t really a moment where all four legs are off the ground as in the other gaits and the legs can only move so fast without looking ‘sped up.’ Conversely, the speed of gallop is largely determined by the shape and unique qualities of the beast. The faster you need the beast to go, the more flexible the spine will have to be, and the greater the squash and stretch. Look for this when watching reference. As the legs bunch up under the beast (the squash) energy is gathered, preparing for a ‘leap’ or ‘stretch’ where the animal can cover as much ground as its form, weight and strength allow. The tighter the squash, the more extended the stretch and the faster the beast can travel.
Gallop cycle animated by Paul Capon on Nico
Variety in the weight or ‘attitude’ of the walk, trot or gallop can be achieved through the shape and movement in the spine and the amount of overlap and follow-through. The amount of flexibility and motion in the spine is key to defining the differences between a horse and a rhino and a jungle cat.
Personality, the key ingredient in any good animation, comes not only from the shape of the key poses but also from what is happening in between the poses. How the character gets from stride to passing can define the character. Are they high-stepping? Straight forward and no-nonsense? Whimsical? Are they flopping around like a puppy or are they hard and densely muscled like a pit bull? The overlapping elements that you’ve added to the animation and their follow-through shows the audience who the character is and what it is made of.
Image adapted from Tiger Locomotion Gallop 01, courtesy of www.rhinohouse.com
Image adapted from Horse Locomotion Gallop 05, courtesy of www.rhinohouse.com
I’ve used these notes to teach beast movement to both students and team members. This article covers the walk cycle. Check back here for more posts on animating the trot, the canter and the gallop cycles!
The adorable monkey demoing the walk is none-other than the star of one of our up-coming games. Rocket 5 would like to thank the talents of Roger Liu and Shaun Budhram for the creation of my sweet monkey-bot, with additional kudos going out to David Huynh for his 11th hour help on Jet-Skate Jo-Jo.
A quick guide to animating animals.
There are a lot of free rigs floating around out there on the internet for animators to practice on. Our friend, the multi-talented Paul Capon, animated a great run animation that is referenced in the Gamasutra article. He used the Nico rig. Rhett the Clydesdale is also pretty easy to use.
So get animating people! Love your craft! And as Don Bluth once said to me: “use reference”.
In This installment of our 2D tutorial series, we will be adding enemy AI to our Lode Runner clone using A* Pathfinding. This post has been guest written by Adrian Seeto of Fun Mob Games who was also kind enough to write the AI scripts that are a huge part of bringing the game to life.
Adding the enemy AI required changes to many of the scripts that we added in the previous tutorials. You can download the complete project here which has been rebuilt to support the new prefab system in Unity 3.5x. If you’re using an older version of Unity (pre 3.5), then you should download this version. You can also follow the steps below to update your existing project. I recommend following along with the tutorial as there’s tons of great information on implementing the AI with A*. You can also play the game as it will be at the end of this tutorial here.
Create an empty GameObject and rename it A*. Make sure it’s positioned at 0,0,0
Drag the /AstarPathfindingProject/Core/AstarPath.cs file onto the A* GameObject
Importing game C# scripts
Many of the scripts have been modified since Part 4 of this series, so you’ll need to update them. If you’ve made changes to your own scripts then you’ll need to merge your changes into these new scripts.
Copy these scripts into your Assets/Scripts/ folder:
Copy this script into your AstarPathfindingProject/Editor/GraphEditors folder:
And finally copy this script into your AstarPathfindingProject/Generators folder:
Configure The xa.cs Script
Create a new Layer by going to Edit –> Project Settings –> Tags and then enter “Enemy” in one of the empty User Layer slots.
Select the Global/Scripts/xa GameObject
Set Ground Mask field to “Ground”
Set Ladder and Rope Mask field to “NoDraw”
Set Enemy Mask field to “Enemy”
Miscellaneous Project Changes
Note that some of these may be unnecessary or redundant depending on how your project is currently setup.
Expand the Global game object in the Hierarchy and then select the “border bottom” and “border top” GameObjects and set their layer to Ground. This is so enemies can stand on it if/when we dig a trap above the bottom border and our enemies fall into it they won’t fall continue through the border into the great abyss.
Select the player object in the Hierarchy and then change its Tag to “Player”
Select the OT/View object in the Hierarchy and uncheck “Always Pixel Perfect“. Note I’m not sure why Adrian turns off pixel perfect, feel free experiment on your own.
Configure A* Pathfinding For Our Level
A* is a graph traversal algorithm widely used in computer science, and commonly used in games for path finding. A full discussion of A* is beyond the scope of this tutorial, but there is some terminology you should be aware of. A graph consists of nodes and the network of connections between them. Once A* has been provided with a graph, you can query it to find the shortest path from one node to another. A* will return a path way list of all the nodes that you must travel along to get from your start node to your end node, in the shortest path possible.
More accurately, the path returned is the “least cost” path, because nodes have a specified penalty cost for traveling along it. A* will attempt to create a path which incurs the least cost. The unit of a penalty is up to the application developer. For example, in an isometric RTS game the terrain tiles would be nodes, with 8 connections per node (except for the boundary tiles). We could have the penalty cost units be related to the time it takes to travel on it. A swampy area might therefore have very high penalties on the nodes in it, while the grass land nodes surrounding the swamp have smaller penalties. A computer-controlled tank which wants to get from one side of the swamp to the other may then plot a course around the swamp if it costs less, even though it is physically further (i.e. more tiles must be travelled, but the total travel duration is less) . Of course, it is up to us as the game developer to implement all the code to actually slow the tank down if/when it travels over swamps, A* is only the pathfinder.
We don’t make use of penalties in this game because traveling along ropes, ladders, the ground, and falling is all done at the same speed. If gravity in our game was a useful non-lethal force (i.e. falling is faster than climbing and just as safe) then we can set node penalties so that A* would return a path where jumping off a platform would be a preferable shortcut to climbing down the ladder. If your game enforces lethal falls from great heights, then you would need additional logic.
A game could have multiple graphs, for use by the various units (ships have different travel behavior to an infantry man for example). For this tutorial, we only need to create one graph. In the graph one node will be created for every tile in a 2d grid-like layout. Each node may have up to 4 connections (up, down, left, right). Aron’s A* Project includes several different path graph generators, such as GridGraph, ListGraph, and NavMeshGraph. The GridGraph is a suitable starting point for our game.
The node connections generated by the base GridGraph are always bidirectional (if it creates a connection from from node1 to node2 then it will also create a connection from node2 to node1) which is not necessarily what we want. Bidirectional paths are fine for ladders, ropes, and the ground because you can go up and down a ladder, and both left-to-right and right-to-left on rope and ground. The problem arises when you want to include fall lanes. A fall lane is a term I’ve made up for a vertical one-way path that you can only travel on by falling. Fall lanes exist under the ropes (you can let go of a rope and fall) and off of cliff edges (you can run off a cliff and fall down to a lower platform). Once on a fall-lane you can’t travel in any direction but down until you’ve hit bottom. This is a uni-directional connection so the nodes on a fall lane only have one connection each: a connection to the node directly below it. Other nodes in the level will have between 2 and 4 connections each.
We could use the base GridGraph and not bother about having any fall lanes, it would just mean that our AI would not plan any paths that involve letting go of ropes or running off platforms. In this scenario you could still have your AI let go of ropes in a “reactionary” manner i.e. if it’s already on the rope and see a player below it, it could let go. You would do this will “special case” code in your enemy AI loop. However, its important to understand this is different from forward planning a route which takes into account the ability to jump off ropes. In order to that kind of path planning with A*, you need to provide that information in the graph, via the fall lane concept.
I’ve created a new generator class called “MyGridGraph” which inherits from GridGraph and overrides the Scan() and IsValidConnection() functions. Our new MyGridGraph class implements the fall lanes idea so let’s add it the scene.
Select the A* GameObject
Click the Graphs -> Add Graph button
Add a new “My Grid Graph”
Width: 26 (these dimensions match our level)
Node Size: 1
Aspect Ratio: 1
Center: 0, 0.3, 0.01 (y is 0.3 so that our nodes are centered in the middle of each tile (which we already previously aligned at 0.3), the z is 0.01 because the integer coordinates used for Aron’s A* node positions have a fixed precision of 0.01 and anything smaller than that would cause troubles.)
Rotation: -90, 0, 0 (rotate x because our grid is for a side-on view rather than the expected top-down view)
Disable Cut Corners checkbox
Connections: Six (we only need 4 connections per node up/down/left/right, but we don’t have that option)
Disable Collision testing checkbox
Disable Height testing checkbox
Level Layers: Ground and NoDraw
Scroll to the bottom and enable the Show Graphs checkbox then hit Scan
If it worked right you should now see the A* graph layout in your game/scene window (enable Gizmos) similar to the following image (click to see a larger version).
The red squares represent nodes that the AI can not travel on. All the bricks should have a red node centered on them. Much of the black “air” tiles should also have a red square gizmo. The tiles without the red gizmos are the nodes the AI can travel on. The blue line represents the connections between nodes. You should therefore see that the AI can travel along the surface of ground tiles, along ropes, and up and down ladders. You should also see the vertical fall lanes under ropes and over the edge of a platform. If you are very perceptive you will see that the blue lines come in 2 thicknesses. A thick line means that the connection is bidirectional (the line gizmo was rendered twice, once each way, making it thicker). A thin line represents a unidirectional connection.
Our enemies and the player classes both derive from the Character class which implements the movement code. In this way we can ensure that the enemies and player move with the same constraints to help prevent giving either an unfair advantage, and just general time-saving and efficiency. The character class does have a movement speed variable, so we can give the enemies different movement speeds than the player, if desired.
Below we create 2 enemy game objects. I’ve just reused the player sprite for them, and I’ve given each one a different tint so I can tell them apart (helpful during the development stage). If you create your own different enemy sprite go ahead and use it.
Create an empty GameObject called Enemies to use as an organizational holder.
Clone the player GameObject in the hierarchy and rename it to enemy-1.
Drag the enemy-1 to child it under your Enemies GameObject.
Drag the /AstarPathfindingProject/Core/Seeker.cs script onto your enemy-1. The script’s defaults are fine. Go ahead and break enemy-1’s connection to the player prefab when prompted. The Seeker provides the enemy with the ability to use A* path finding. It has gizmos which paint green lines representing the found path.
Expand the enemy-1 GameObject to see it’s children.
Delete the “shoot parent” child.
Add an empty GameObject child under enemy-1 named “path target”. Local Position 0,0,0 Local Scale 1,1,1. This will be a transform that the enemy script will move around to place on the desired target for our path finding AI. Useful during debugging to see what it is targeting.
Duplicate “path target” and rename to “tile bounds”. Add a box collider to it, set to Trigger and centered at 0,0,1 and scale 1,1,1. This is so that when we trap an enemy we can walk smoothly on top of it’s head as if it was ground.
Select the enemy-1 game object and set its Layer to Enemy and apply to children. Set its Tag to Enemy (leave children untagged).
Expand the enemy-1 Player script component. Drag the /Scripts/Enemy.cs script onto the Player Script field to replace it with the Enemy script.
The Enemy script has 3 slots that need to be filled: Player and Player Tr (drag the player gameobject to those slots), and Target (drag the path target gameobject to this slot).
Expand the enemy-1 OTAnimatingSprite script. Set the Material Reference slot to “tint”. Set the Tint Color to red (or your preference) to visually differentiate it from the player.
Clone enemy-1 as enemy-2 and give it a green tint. (You may have to redo the Red tint on the other enemy due to an OT quirk).
Drag the enemies to suitable spawn points in the scene.
Optional: Select the Enemies root GameObject. Drag the ChangeBehaviors.cs script onto it. Set the Enemies array size to 2, and drag enemy-1 and enemy-2 into the slots. This script will allow you to modify an enemy’s behavior on-the-fly via GUI between a “plain A* to Player” and a “Lode Runner-esque” behavior. The A* to Player behavior simply follows the shortest path toward the player’s exact position. The Lode Runner-esque behavior still uses A* but also tries to reimplement some of the reactionary quirks of the original game, especially with regards to ladder use. See the Enemy.cs file for details. You can disable/remove the ChangeBehaviors.cs script when you are done testing it out.
While the enemy AI is not a completely faithful recreation of the original, it is hoped that it will provide you with enough of an idea on how you can use and implement A* path finding in your own creations.
If you have any questions about the tutorial, please let us know in the comments below. Your support helps to keep these tutorial coming so be sure to follow us on Twitter and Facebook. This blog post is part of iDevBlogADay, a collection of indie developers writing about their development experiences.
Alien Booth: Transform pictures of your friends into awesome aliens!
iSpoof Walken: A hilarious look into the world of Christopher Walken!
Gaga Eyes: Transform pictures of your friends to give them huge anime eyes!
About the author
The AI scripts and this tutorial were contributed by Adrian Seeto of Fun Mob Games, creators of Pocket BMX game for iOS, a free-roaming 2D bike tricking game with physics. You can check them out at FunMobGames.com or on twitter @FunMobGames.