Category Archives: Games

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.

Game Engine Comparison

JavaScript has exploded in popularity over the past few years. It’s now the number one language on Github, and getting more popular every day. This popularity plus the recent advances in HTML5 has meant an explosion in the number of JavaScript game engines out there. The JavaScript wiki lists over 80 game engines, where to even begin in choosing one?! Let’s not complain too much though, this is a great problem to have, HTML5 gaming has arrived!

Today we are going to compare three popular JavaScript game engines: CraftyJS, ImpactJS and LimeJS. You really can’t go wrong with any of these great choices, but they do have their own strengths, weaknesses and style. Taking some time to get to know what’s out there is well worth it before embarking on a game.

Why These Engines?

In short, because they are popular. Before embarking on this article I made a spreadsheet that calculated which JavaScript game engines are the most popular on Github; Lime and Crafty took the top two spots. I also decided to go with Impact for the third engine, even though it’s not on Github, due to it being commercial. Impact proved to be a good choice as it often takes a different approach on things from the other two, offering some nice contrast in the comparisons.

Breakouts, the “TodoMVC” of JavaScript Game Engines

JavaScript’s popularity hasn’t just meant an explosion in game engines, all kinds of JavaScript libraries are popping up. MVC type frameworks for rich internet applications in particular are a dime a dozen these days, which one to choose? Addy Osmani and Sindre Sorhus addressed this problem by creating TodoMVC. Basically, they gathered implementations of a simple todo application in many different MVC frameworks. TodoMVC has become a great resource for comparing and contrasting all these frameworks, and lets developers get a feel for which frameworks speak to them the most. This also comes with the added bonus of having a decent little application written in the framework of your choice to get you started.

I thought it’d be pretty cool if we could get a similar thing off the ground for JavaScript game engines. By implementing a simple, but non-trivial, game in as many JavaScript engines as we can, we can help people get a feel for which engine they like and which one meets their needs.

Addy and Sindre chose a pretty dull and straightforward application: a todo list. That was a good choice. The application itself is not the point, but rather the frameworks. I made a similar choice with the game engine comparisons, Breakout:

It doesn’t get much more boring or straightforward than Breakout! But really, this is a perfect choice here. Breakout is simple enough to easily wrap your brain around, but at the same time it involves player input, sprites, animation, menus, collision detection, power ups and sound effects. Not to mention, it’s a great launching point to extend and add more features to, should you want to get to know a specific engine even better.

Natural Systems in a Web Browser

A few nights ago, I plugged in a brand new projector into my laptop. After playing a simulation against a wall for a few minutes, I adjusted the unit and inadvertently cast the projected image on the floor. Out of nowhere my cat ran in and began to pounce on the dancing sprites as they swept across the carpet. She was fully convinced our bedroom had been invaded by colorful, bouncing insects and was doing her best to catch one.

I’ve spent the better part of a decade trying to code natural looking movement in a web browser. What I was witnessing felt like a huge victory. My feline QA team was hard at work batting down digital fireflies while I thought about the threshold of belief. What were the compelling qualities of the system I created that convinced her these targets were real enough to attack?

I’m not the first person to consider how we perceive our natural world and how we distinguish imitators. In ‘Vehicles: Experiments in Synthetic Psychology,’ Italian neuroscientist Valentino Braitenberg examines the fine line between accepting a natural versus designed system. It turns out, humans are pretty easy. It doesn’t take much for us to recognize natural movement. We’re fine tuned to a combination of special qualities. Add a few simple rules together and we’re more than ready to suspend our disbelief.

I define a natural system as a sum of forces acting on autonomous agents. The system contains a collection of independent objects that follow rules designed simulate the natural world. The rules are the key. How do we build and execute instructions in a web browser with enough realism that it throws a house cat into a spasm?

Why web browsers make this difficult

Before we start, it’s worth understanding why browsers make this a difficult task. Moving forward, we’re going to lean heavily on JavaScript and DOM manipulation. JavaScript and the DOM are built on an event model. Users do things. Browsers respond. We want the reverse. Right out of the gate we’ll animate objects at a lifelike 60 frames per second with no end in sight.

Browsers also juggle multiple tasks with competing priority. As much as we’d like it, they do not allocate all of their resources to rendering graphics. There’s a network to manage. It is a web browser after all. While we’ll attempt to focus the browser’s attention on drawing our system, we’ll never divert it from other system-level distractions.

Luckily, browsers have made a few advancements to overcome these hurdles. As we construct our framework, we’ll make use of the requestAnimationFrame API to optimize our frame rate. We’ll take advantage of hardware acceleration for an added boost. We’ll use vector math and model our system after a sum of forces. Finally, we’ll incorporate physical input via accelerometers for added realism.

The Big Picture

Our framework’s architecture will take a cue from procedural drawing programs like Processing. When we draw procedurally, we repeat two steps in a loop. First, we run a step function that calculates changes in our objects’ properties. Second, we translate those changes into style properties and render a new frame. If we manage to do it fast enough, we create a beautiful natural looking simulation.

At a high level, we’ll separate the system into three main components, System, World and Item. We’ll also build out some utilities and a Vector class to make our life easier. Ready to get started?

Our Project

To begin, we need to organize our project as a simple web page. Create a folder called SimpleSim with an index.html file. Also create a blank file called main.css and a blank file called simplesim.js. After this first step, we’ll do almost all our work in the simplesim.js file.

We will also make use of Modernizr to detect if our browser supports css transforms. More on that later. For now, download the latest Modernizr and place it in your project folder. To save on file size, if you’d like to create a custom build of Modernizr, select ‘2D Transforms’ and ‘3D Transforms’ as configuration options.