Monthly Archives: March 2017

Intuitive Player Character Movement

Recently, I released Empty Black, my 2D shooter/puzzler/platformer. In this article, I’ll describe how I made the player movement deft and intuitive. Play the game before you read on, so you’ll know what I’m talking about.

My general approach was to change something, then try it out. I took the ideas for adjustments from several sources.

One. I examined the parameters affecting the movement of the player characters in other 2D platformers. Is the floor slippy? What is the ratio of sideways movement to jump height? Does the character accelerate as it moves? Is the character’s jump height affected by the length of time the player holds the jump button? Is the character slowed when it bumps into a moveable object?

Two. I examined the unusual behaviours of the player characters in other 2D platformers. Super Meat Boy makes the character leap away from the wall automatically when wall-jumping. Spelunky lets the character pull himself up and over ledges. In Castlevania, the character can do an extra jump while in mid-air.

Three. I got people to play test. Kemal told me that the character movement should be effortless. Specifically, if the character hits a wall near the top, it should slip up and over. Ricky told me it was weird that the player had no control over the height of the character’s jump. He showed me how, when hopping over an obstacle in a room with a low ceiling, he bumped his head. Ricky also pointed out the jarring effect of the initial slow down of the character when it lands after a jump. Everyone told me that airborne movement was too sensitive. Everyone told me that wall-jumping was too finicky.

Four. I read pieces written by programmers about their character movement algorithms. These pieces were mostly confined to short comments, rather than in-depth analyses. Hence, this article.

To the algorithm.

The short version: a pile of hacks.

The long version:

The player presses the jump key. The first question is: can the character jump? Which means: is the character in contact with anything that can be used as a place to jump from?

Empty Black uses Box2D to control the physics of the game world. Any movements are subject to Box2D’s models of the forces of friction and gravity. Further, Box2D handles the reactions of objects that collide: bounces, shoves, spins and slides. The game can interrogate Box2D and ask what objects a particular object is touching. If the character is currently touching something solid, the character may jump.

Except, it’s not quite that simple. As well as leaping from the ground, the character can wall-jump. This means landing and clinging onto a wall, then jumping again, away from the wall.

Systems From the Ground Up

When it comes to creating games, I am more comfortable slinging code around than creating the visuals. I am always interested in techniques that fall within my comfort zone yet boost my game’s graphical umph. Particle systems are one such technique. By creating a small physics system that throws around hundreds – even thousands – of tiny little particles, awesome visual effects like smoke, fire, sparks, rocket exhaust and many more can be created. They are simple to create and really add nice visual effects to your game. Not to mention particle systems can be given physical properties and participate in your gameplay. In this article we’re going to walk through many of the details and considerations in a typical 2D particle system.

Above is a particle system configured to look like a meteor. You can pick from several other particle systems from the dropdown as well. In all cases the same engine is driving the particle systems, just using a different configuration each time. It’s pretty nice that one system can produce such a variety of visual effects!

Despite their slightly intimidating name, particle systems are very common these days and simple in concept. Most game engines have particle systems baked in. Unfortunately for HTML5 game engines, this often isn’t the case. This is partly due to most HTML5 game engines being a bit on the young side, but also and due to the fact that historically canvas has not been performant enough. In modern browsers, canvas’s performance has improved quite a bit, and adding particle effects to your HTML5 game is pretty doable (but there are performance considerations, see the performance section below). Even if your favorite engine of choice doesn’t include built in support, it’s easy to roll your own. We’ll start with a very naive system that gets the basics down, then talk about more interesting features that are commonly found.

A quick note, the particle system engine used throughout the article is heavily inspired by Cocos2D’s particle system implementation. Even the above examples should look pretty familiar to Cocos2D users. I thought due to Cocos2D’s popularity, it made sense to follow closely to what they’ve done. So a quick shout out to Cocos2D, thanks guys!

A Naive Particle System

To begin our simple particle system, let’s define a Particle type. We need to know where the particle is and where it’s headed; in this respect, a particle is not much different from any other entity in a game. We also want each particle to only live for a certain amount of time. So with that in mind we can start out with:

Nothing too exciting going on here, but it’s worth pointing out that the constructor takes an angle (in degrees) and a speed (in pixels per second) and converts these values into a velocity vector. This is intentional, when setting a particle up it’s easier to work with an angle and a speed. But when updating the particle each frame, it’s easier to work with a velocity vector.

Reacting to each other realistically

One of the most complicated and math-intensive components of game development is collision detection and response. If all you need is to calculate when a couple of rectangles overlap, it’s not a big deal, but for games that involve lots of irregularly shaped sprites moving and reacting to each other realistically, you’ll want to use an industrial strength tool to get the job done.

Enter the physics engine.

The idea behind using a physics engine in your game is that instead of hacking together a very-loose approximation of how real objects might interact for your game, dropping in an engine whose sole purpose is to run the physics simulation allows you to leave it to the engine to handle object dynamics and interactions and concentrate on the game itself.

To this end a number of different Physics engines, both 2D and 3D have made their way to JavaScript, many of them ports from other languages, but some written from scratch. For an overview of a number of different engines, take a look at Chandler Prall’s JavaScript Physics Engine Comparison.

Of the myriad of open-source 2D engines that are available, one stands out: Box2D. One reason for this is that it was used as the simulation engine behind mega-hit Angry birds, whose physics-based gameplay required a bullet-proof physics implementation. Box2D is the 2D physics engine of choice for many games, and thus was ported wholesale over to Flash and ActionScript a while back. To get a JavaScript version, some ambitious folks have taken advantage of the similarities between ActionScript and JavaScript and created a converter that converted the ActionScript to JavaScript.

There are a few ports floating about, but the most popular one is Box2DWeb:

Some work has also been done to convert directly from C++ to JavaScript using emscripten (See box2d.js) but this has a different API than box2dweb and doesn’t appear to be kept up.

Box2DWeb doesn’t have it’s own documentation per se, but it shares the same API as the Flash library it was converted from, so the Box2DFlash Documention can be used to figure out the Box2DWeb API. If you’re interested in really diving into Box2D, the official Box2D C++ manual also makes for a worthwhile read, although it contains some newer features not found in Box2DWeb.

A Post Mortem

Building cross-browser, cross-device games for the open web does not have to be a tedious process. In the last week of March 2012, Bocoup held an 8-hour hackfest for its employees, during which time I built a cross-device multiplayer game that works on Firefox, IE 6+, Chrome, Opera, Safari, iOS, Android, and Windows Phone 7. Granted, the game is probably not what you’re imagining when you think cross-device multiplayer game, but the point of this article is that properly chosen constraints can help you develop really cool things in a very short amount of time.

Defining the project

Sometimes you choose your constraints, and sometimes your constraints are given to you. The primary goal for this project was to develop a game that could be played at JSConf. I knew that I only had 8 hours to develop the game, so I knew that I would have to keep things as simple as possible. Whenever I’m not working with an artist, I try to go for something minimalistic, but visually striking. That way my lack of artistic skills can be masked by the striking design. The first thing that came to mind was Paper.js, an “open source vector graphics scripting framework that runs on top of the HTML5 Canvas.” Their examples galleryis full of smoothly animated, stunning demos.

My favorite Paper.js demo has always been their most basic: the Chain demo is just a simulation of a rigid-body chain, rendered as a kind of noodle that you control by moving the mouse. Even though there’s no game to it, it’s fun to play with the demo for one or two minutes and see how the noodle reacts as you move it around and fold it back in on itself. I figured this would be an excellent starting place for a simple game: when the basic act of movement is something that makes you smile, it only takes the barest of game mechanics to create a compelling experience on top of it.

Once I decided to go with the Chain demo as a starting point, the gameplay suggested itself: Snake, the classic game where you control a snake trying to eat little powerups, growing longer and longer as you progress.

Next up, I had to consider the environment the game would be run in: a large lecture hall with a projector. I was inspired by Renga, a game by wallFour meant to be played by hundreds of people with laser pointers that I saw demonstrated at the Experimental Gameplay Session at the 2012 Game Developers Conference. Building off of Renga’s core concept, the game would happen on the projector, and audience members would play using a client they load on their laptop or mobile phone.

The initial vision for the game was simply Snake, but collaboratively controlled by the entire audience. The audience would be presented with up/down/left/right controls, and the snake would average out everyone’s contribution to its velocity vector and move in that direction. For example, with 6 people voting up and 1 person voting right, the snake would move mostly up with a slight drag to the right. One thing this meant was there would be no movement grid as you would find in traditional Snake. All the better, as that’s one more thing I didn’t have to code!

Lighting in Games

Setting the right atmosphere and mood is important in any type of game. From Myst-like puzzles to real time strategy to first person shooters, lighting plays a huge role in how players interact with a game’s world are impacted by it. Mysterious and horror games meant to keep players on the edge of their seats usually have darker environments, punctuated by brighter areas and objects to ensure you notice them. Other genres tend to use more balanced lighting systems, and games that are praised for their appearance masterfully paint their worlds onto our screens, the environments telling stories of their own. Lighting is a topic which merits an in-depth study all on its own; most artists spend years mastering the subtleties of light and color. This article will introduce you to the key concepts of light in computer graphics and how to use it effectively.

Many different considerations go into lighting of any kind, be it for games, movies, or even in well-architected buildings. Every AAA game I have read the credits for has had at least one lighting director; these people make sure every inch of graphics look their best and contribute to the story. Think about this for a moment – there are people whose primary job is studying how things look and tweaking environments to get the best possible result.

Big games have lighting directors is because light is a complicated topic, both in the real world and in computer graphics. In reality, light travels from its source and is reflected, scattered, and/or refracted for every surface it encounters. Realistic modeling of light in simulations is called ray tracing and can generate very lifelike images by casting rays into the scene to calculate physically-correct lighting. Ray tracing’s downside is that it cannot run in real time on today’s hardware. In fact, a single ray traced frame can take hours to render, although some implementations for games can achieve frame rates up to 20FPS (Intel’s Quake Wars: Ray Traced and nVidia’s OptiX).

Instead of sending millions of rays into a scene, most games use a method where each object is individually sent to the GPU where it is mapped into 3D space and rendered. Creating refractions or reflections can be difficult when using this method because models do not have information about any of the objects around them. Games have been using this technique for decades and graphics cards provide dedicated pipelines for drawing objects this way.

There are a few standard ways to calculate how light illuminates a surface, and while there are numerous variations within each method, we’ll look at the most common configurations. The first of these is a very simple model known as Lambert lighting, named after Johann Lambert who described the idea behind it in 1760. Objects lit in this way are called Lambertian and emit light evenly across all viewing angles. This means that different points on an object will look the same no matter what angle they are viewed from. Thus, the Lambert model is used to render objects which have only diffuse lighting, where there is no glossiness or reflections.

To be able to calculate the lighting at a point on an object we need to know a few things about the light and the object. First we need to know the position of point on the object relative to the light source, which is found by light_position - point_position. Second, we need to know the normal vector of the object where we are performing the calculation, which tells which direction the surface is facing. Once we have this information Lambert lighting is very easy and intuitive to calculate. Simply put, surfaces directly facing the light are fully lit and the amount of lighting falls off linearly as the normals turn perpendicular to the light. To determine if two vectors, such as the surface normal and the light direction, are in the same direction we need to find the angle between them. This is very simple to calculate and the result is called the dot product of the two vectors. First we normalize both vectors so each one has a unit length of one, then the dot product can be calculated as Ax*Bx + Ay*By + Az*Bz. The dot product of any two normalized vectors will be a value between -1.0 and 1.0, where 1.0 means the vectors are pointing in the same direction, 0.0 indicates they are perpendicular, and when the dot product is `-1.0’ the vectors are pointing in opposite directions. This result fits perfectly when calculating Lambert light where we want to know the relation between the light direction and the surface’s normal vector.

Games at a more fundamental level

As game developers, we often talk about the technical aspects of building games; but every once in a while I think it’s prudent that we discuss games at a more fundamental level. Today, I’d like to talk about how games become fun.

This is certainly a divisive topic, and clearly there’s no one answer. There’s no formula you can follow, no library you can use to “import fun”. When I was doing the research for this article, I asked my friend what he thought and he said “that’s like asking a comedian how to be funny”, ­­the implication being that it’s much more art than science.

There are surprisingly few people studying the fun of video games, considering the market size and broad applications of the ability to make things fun. But the (growing) few who have studied this have certainly come up with interesting observations.

The brain is a pattern learning machine.

The human brain excels at discovering and remembering patterns. It’s what we do all day long. Whenever you recognize an object or a person, that’s your brain calling up a previously learned pattern. The same holds for whenever you perform a task, write an article, do a skateboard kickflip, or drive to your parents’ house.

Since pattern learning is so important for your survival, your brain has a way to reward you when you learn a new pattern: it releases dopamine. It feels good to learn something new! That’s your brain’s way of incentivizing you to keep learning stuff. And for good reason; learning things is hard, and if there were no incentive, we’d just sit around staring at the wall all day.

Game designers ended up taking advantage of this learning/reward mechanism. It feels great to discover a new secret in a level, it’s really rewarding to figure out Bowser’s movement pattern and finally defeat him, and “getting the hang” of the games controls is a good feeling.

Now we understand that we should give our players patterns to learn and master, because learning those patterns is satisfying and fun for the players. But patterns that are too difficult to learn are a turn­off. Have you played Dwarf Fortress yet?

To avoid overwhelming players with brand new patterns and concepts (or, “game mechanics” and “ludemes”) for each game that gets built, it may be better to simply evolve upon game styles and mechanics that are already out there. Players won’t feel alienated or in over their heads, but they’ll still get the joy of learning a game’s new take on a mechanic, or a unique combination of game mechanics and ludemes.

It should seem natural, then, that as games evolved, so did their mechanics. Every once in a while a game would come out that invented a new mechanic, but more often than not, new games would simply expand upon an existing mechanic or try to combine established mechanics in new ways.

When Pong came out, it popularized the “ball and paddle” mechanic. Eventually, someone said “we should make a 1­-player Pong”, and invented Breakout. It still used the ball and paddle mechanic, but the opponent was a brick wall instead of another paddle. Thus was born a unique game that nobody had ever seen before, but the core mechanic was still familiar to players.

Donkey Kong popularized the platformer mechanic, and a few years later Mario added to that with more in­-depth gameplay and a few other mechanics (the “secret area” mechanic and the “player upgrade” mechanic, for instance).

The Legend of Zelda popularized the open world RPG mechanic, and also brought in the melee combat mechanic, player upgrade mechanic, secret area mechanic, and even an in­-game currency mechanic (some of which had already existed, others were new at the time).

If Zelda’s mechanics all sound familiar, that’s because they’re still in use today! Those mechanics have been used over and over again, in different permutations, in many games since then. Those mechanics are also seen in the Elder Scrolls series, Diablo, and even Grand Theft Auto. Those best­sellers didn’t need to re­invent the wheel: they just needed to concentrate on great story, gameplay, and immersive worlds. Magic, experience and leveling, currency, melee combat, open worlds, and non­linear story were all established game mechanics by that point.

It might seem that the two things I’ve talked about­­ “make your players learn new patterns” and “use established patterns so as not to alienate players”­­ are statements at odds with one another. However, they form a nice thesis: games should be easy to learn and difficult to master. (“Should” is a strong word; I’d rather say that many­­–but not all­­–groundbreaking games were easy to learn but difficult to master.)

Easy to learn, difficult to master.

Mastery is much more than being able to beat a game. Mastery comes from having a deep understanding of the underlying mechanics of the game, and using that to not only beat the game, but to do it handily and gracefully. This also implies that a game that can be mastered has a certain level of depth, and that allows its players to keep coming back and try to learn more about the game.

Chess is the ultimate example of this mantra. There are only 12 or so simple rules that define the game of chess (7 for movement, and a couple extra for check, checkmate, castling, pawn promotion, and something called “en passant”, which I hadn’t heard of until now). But mastering chess takes years of dedicated practice and learning. And because the simple rules combine in so many different ways, almost every chess game is different, giving it infinite replay value.

Compare chess to tic­-tac­-toe, which is “easy to learn; no mastery”. You’ll play it a couple of times when you’re bored, but it’ll never be a game you spend too much time thinking about. It’s also not really fun. It’s easy to learn, but there’s no depth and very little replay value.