What is a game engine?

In this article I'm going to explain what a game engine is and why it's useful. When I first started game design many terms confused me. I heard: game engine, sprite, game loop, physics engine, Cocos2D... I had a rough idea of what they were but not how the concepts fitted together. With the benefit of the experience I now have, I'm going to explain what all this things mean and how they fit together. This guide is designed for people who are new to game design and will focus and iPhone and Android operating systems. I'll also give an overview of my favorite game engines for each platform.

How a game works

Games can range from simple to extremely sophisticated but at the most basic level every game performs the same core functions. All games take inputs from the user, using those inputs they work out what effect it has had on the game state, finally they display or animate something on the screen. After this, the process is repeated until you either win or fail. Lets take the example of Angry Birds for iPhone. The game starts by setting up an initial game state. In this case it gives you a certain number of birds and a pile of wood and pigs to destroy. At this point the game waits for input. If you don't do any thing the game just stays as it is. When you touch the screen and pull back the catapult the game is responding to your input and changing the game state accordingly i.e. the postion of the catapult. When you let go the game keeps going and calculates what will happen. The bird collides with the structure and the wood responds realistically. When everything has stopped moving the score is calculated and the game is over.

This is simple enough but how could we go about coding this? In programming terms, when we want the computer to repeat something over and over again we use a loop. For games this is called the game loop. Inside the loop we perform all the things we need to do to make the game work. We listen for inputs, calculate how those inputs affect the game state and finally update the screen so that it correctly displays the game state. Below is a simple representation of the loop:

  1. while (gameIsRunning) {
  2. // Check for inputs
  3.  
  4. // Calculate change in game state
  5.  
  6. // Update display
  7. }

If we were making a simple chess game here's what the steps would look like:

Check for inputs

The method we would use to check for inputs would depend on the system we were using but in general it's necessary to register the code as a listener with the operating system. A listener is just a piece of code which is notified when a user input happens. To display something in iOS you need to use a view. View has three methods called touchsBegan, touchesMoves and touchesEnded. If you override one of these you can write whatever code you want inside the function to respond to the touch. For the chess game we would check if the touch happened over a piece. If so we would mark that piece as selected. As the finger was moves, the position of the piece would be updated so that it moved with the finger. When the touch ended the piece would be released.

Update game status

For each loop, the game status would monitoring what effect the input had on the game state. If the touch ended we'd need to check to see if the final position was valid. If it was valid, we'd trigger the next players go. If not, we'd need to return the piece to it's original position and notify the user. Every loop, It would also be necessary check if the end of the game had been reached.

Updating the display

As the piece was moving, the display would be responding by rendering the piece in a slightly different position each frame. Having a series of smoothly changing images causes a smooth animation. Because computers are very fast normally it's possible to go through the game loop 60 times every second. Running at 60 times makes our animations smooth. If we put lots of complex code in the update section it could cause mean that our loop could only run 20 times a second which would make the game seem jerky and unresponsive. This can be seen on some games as slowdown when there are lots of things happening at once. It's important to remember that to run our loop 60 times a second i.e. have an animation of 60 frames per second (FPS), we only have 0.016 second per loop to play with. That's why writing efficient code is very important in games.

Hopefully this gives you a basic understanding of how a game works. Next we're going to look at what a game engine does for us.

So what is a game engine...?

A game engine is framework which facilitates the kinds of tasks which need to be done when writing a game. So what are the kinds of tasks we want to do? We would probably want to display images on the screen (in game terminology, an image which is displayed on the screen is called a sprite). We may need to draw menus or text on the screen. We might want to organise our sprites so that some are behind others. Often games use realistic physic so objects collide or fall with gravity. A game engine will help us do these things and many more.

You might be thinking "Is that all it does? That doesn't sound too hard. I'd prefer to make my own game engine". That's fair enough and it is possible to write your own game engine. When I was learning game programming I wrote a simple game engine to get a better understanding of the fundamentals. However after that, I decided to learn how to use game engines and since then I've not looked back. There are huge advantages to using a game engine which I will illustrate with an example.

Example 1: loading a sprite

In Cocos2D which is arguably the most popular game engine for iPhone this is how a sprite can be loaded into the game:

  1. CCSprite * sprite = [CCSprite spriteWithFile:@"sprite.png"];
  2. sprite.position = cpp(100, 100);
  3. [game addChild: sprite];

This code loads a sprite from a png file, sets it's position to (100, 100) and then adds it to the game. Now lets look at what Cocos2D is doing behind the scenes.

Cocos2D: checks the file name is not null, checks to see if the same image has been loaded before (if so it will automatically the previously stored texture), converts the image to a texture which can be rendered by the graphics card (this step alone is over 100 lines of code), performs fixes for certain types of image files and certain iOS versions, creates a square which the graphics card needs to represent the image, transforms the square using OpenGL ES (a low level graphics library) so that it's at the specified coordinates and finally adds the image to the game.

Phew... As you can see Cocos2D is doing a lot behind the scenes so that you only need to write three lines of code. Because of this, development time and code complexity are significantly reduced. The other point, is the amount of expertise which has gone into writing the game engine. The people who've written this system are experts. Because of that they'll write efficient non-buggy code. By using a game engine you're leveraging the expertise of a whole community of experts. Which means that you can focus on game design rather than the intricacies of graphics programming.

Features provided by a game engine

In this section I'll give an overview of the standard features provided by a game engine

Graphcs

As I explained earlier, game engines provide assistance rendering sprites to the screen. But that's not the end of it! Normally it's not efficient to just load images into your game one by one. The best way is to put all your images onto a big image sheet and then load that one image. When you need one of the images it can be cropped from the sheet. This would be difficult to implement from scratch but in a good game engine like Cocos2D or LibGDX it's taken care of for you. They also allow you to create frame by frame animations from these sprite sheets. If you want to make your character walk you can provide images of the character in all the stages of walking. The game engine can then loop through these images to create a walking animation.

Game engines also provide more complex features.
LibGDX for Android, completely shields you from how the graphics are implemented. This means that during development you can run your game as a native Windows or OSX program on your computer thus avoiding the slow buggy Android emulator.

Game engines also provide help with animations. Cocos2D proves a number actions like CCMoveTo and CCFadeOut. You can create an action which will send your sprite from one location to a different location in a specified amount of time or to fade out your image. You can also create a sequence of actions to be executed one after the other. This saves you having to write your own classes to update the objects position every frame.

Game engines also help you organise your game. You can create scenes which contain layers. Each level can be represented by one scene and the background can be on a different layer to your player. This helps to keep your game organised and reduced the complexity of the code.

Sound

All games need audio. Sound effects for when the player bumps into something and background music to create an atmosphere. Game engines facilitate this by shielding you from the base implementation (i.e. a hardware library like OpenAL). In Cocos2D playing a sound is as simple as:

  1. [[SimpleAudioEngine sharedEngine] playEffect:@"boomSound.caf"];

And in LibGDX:

  1. Sound boom = Gdx.audio.newSound(Gdx.files.internal("BoomSound.wav"));
  2. boom.play(1);

Another handy feature is the ability to stream sounds. For your background music you don't want to load a 5mb file into memory. By streaming you can play the background music bit by bit and save memory. In Cocos2D this can be done with one line:

  1. [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"background-music-aac.caf"];

So you can see that game engines make sound effects very easy.

Physics

All good game engines come with physics built in. Physic is a term which covers a wide variety of functions including: detecting collisions, applying forces and velocity to objects. Using a physics engine you can define your shapes and watch them respond like real world shapes would. Angry birds relies almost entirely on physics for it's game play. A physics engine will let you know when a bullet hits your player. It can automate an arm withs spikes to spin round. It can create a wobbly bridge or a water effect. Working these things out yourself is very difficult and would require a minimum of a degree in Maths of Physics. Luckily by using a pre-made, free, physics engine you can get straight into creating your game. In my opinion the best physics engine is Box2D. It's very powerful, has implementations for iPhone and Android and is included in all the best game engines. The benefit of using a very popular cross platform engine like this is that when you move from Android to iOS you don't need to re-learn how to use the physics engine!

Particles Emitters

Particle emitters allow you to create a huge range of effects for your game. You can create explosions, water effects, rocket boosters and many other effects. An emitter sends out a stream of coloured sprites who's speed, direction, lifetime and colour can be altered. Game engines usually have particle engines built in. Cocos2D is particularly good for this. For $7.99 you can buy ParticleDesigner, a program which allows you to interactively create particle effects and then save them to file. These can then be imported into Cocos2D with only a few lines of code:

  1. system = [CCParticleSystemQuad particleWithFile:@"particle_def.plist"];
  2. [game addObject:system];

User interface

The final area I'm going to cover is the user interface. Game engines provide an easy mechanism to draw scores and create your game menus. Drawing text manually is very complicated. You have to load a big sprite containing all the characters you need and then manually map each letter to the coordinate of the letter in the sprite sheet. Fortunately, game engines take care of this too. They will load a font definition from the common True Text Format then allow you to choose the colour and font size an display the text for you on the screen. In Cocos2D you can then animate your text using the built in actions. In Cocos2D you can draw custom text as simply as:

  1. CCLabelTTF _score = [CCLabelTTF labelWithString:@"0" fontName:@"score_font" fontSize:50];
  2. _score.color = ccc3(255, 0, 0);
  3. _score.position = cpp(100, 100);
  4. [game addChild: _score];

Using a game engine you can then automatically create menus with your custom text which activate when the user clicks them.

Final thoughts...

In this article I've given a very brief overview of what a game engine is. I've not covered everything but this article should give you the conceptual framework to start writing games using a game engine. As you'll have noticed, in this guide I've mentioned Cocos2D and LibGDX.

Cocos2D for iPhone

Cocos2D is the game engine I use for my iPhone development. It's powerful, efficient and very feature rich. I especially like it's intuitiveness. The game is arranged into scenes and each scene has layers which can be used to arrange the game elements in the z-direction. All visible objects are nodes which can be added to layers and scenes. Cocos2D also includes the very fast and cross platform physics engine Box2D. Because it's so popular Cocos2D, there are lots of tutorials and guides available as well as support from third party applications like the excellent ParticleDesigner and TexturePacker. The library is free and can be found here

LibGDX for Android

Android is written in Java which is a higher level language than the iPhones Objective C. This tends to mean that things run slower on Android than on iPhone. For this reason I use the most efficient game engine which is LibGDX. LibGDX is low level which gives you a lot of control and includes a native version of the physics engine Box2D. This version of Box2D provides a Java interface to the fast native C library (it's much faster than the version written in java JBox2D). Aside from that, the library also provides all the sound, scene management and graphics features you'd expect from a good game engine. The library is free and can be found here

Overall, I'd highly recommend using a game engine to improve the quality of your game and speed up development time. If you have any further questions feel free to comment on this article.

Tweet: 

Comments

I like ur blog :) is fantastic! is very uselful and interesting. I'm goig to create my own game engine with this thanks a lot Ben

I was tasked with developing a game engine and wasn't sure what id gotten myself into. Now I know, thanks for the informative post.

Awesome tutorial.. now i understand what is game engine.. thanks a lot .

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. The supported tag styles are: <foo>, [foo].
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.