A Game Design Tip A Day #4 – The Wrath of the Garbage Collector

In many programming languages, there is something called the garbage collector. No, not the truck that comes by your house every week to collect your empty pizza boxes and energy drink cans. When you create objects, generally speaking they are added to what’s known as the heap, which is like a big pile of data used by all your programs. When you’re done using a piece of data, then the garbage collector comes along and frees up that memory for re-use later; without it, the heap would soon fill up with gunk and memory leaks and your computer would probably crash. And that’s bad.

There are certain operations notorious for garbage collection. One of those, in most languages, is string concatenation. Strings, as you’re probably aware, are objects. Like all objects, they occupy space on the heap. When you concatenate two strings together, it’s a common misconception to assume there isn’t much overhead and you’ll just be getting a bigger string back out. However, since strings are usually immutable (once set, their values can’t be changed – this is the case in languages such as Java and C#), you’re actually taking the two original strings and creating a third immutable string which contains the contents of the original two (or three, or four etc). You might see something like this in code (this example is specific to Unity C#):

tip_a_day_04

and think it looks reasonable – it’ll print the line “Player John has 0 health”. However, you’re taking five strings – “Player “, “John”, ” has “, “0” and ” health.”, and then creating an entirely new string to print. What’s worst about this is since “Player “, ” has ” and ” health” were created on-the-fly and are no longer needed, they need to be removed from the heap, which means the garbage collector is called and we waste a load of time cleaning up space we didn’t need to allocate in the first place. A better solution would have been to cache those three strings somewhere (such as in their own variables) so they’re not wastefully created and immediately removed again. That also has the advantage of removing the overhead of creating them each time, especially if PrintStuff() were called frequently.

A Unity-specific warning zone for garbage collector abuse are the Instantiate() and Destroy() functions (although all scenarios in which objects are made and destroyed have the same effect). A common operation in games, for example enemy spawning or playing particles, is to create them when required using Instantiate() and then remove them once they are no longer needed using Destroy(). Each time Instantiate() is called, there is overhead for creating the object, and when Destroy() is called, the garbage collector gets involved. This means that overuse of these functions can lead to a significant performance decrease. It’s like how capitalism works – why re-use this old thing when I can buy a new one?

A much better way of working with multiple objects this way is to utilise object pooling; that is, we create a bunch of objects at the start of the game in a disabled state, enable them when we’d usually have instantiated them, then just disable and reset their parameters ready for re-enabling, when we’d previously have destroyed them. We still have a large overhead at the start because we need to create everything, you need to make the pool large enough for the maximum number of objects you’re likely to need (or the pool has to be extendible) and there’s only a point to this if the speed improvement is significant (on small object sets, this could actually be slower), but in games where things are frequently spawning and disappearing, object pools are more likely than not the way to go. Besides, it’s more amusing to code up a really big pile of stuff than an boring old create/destroy cycle. Yaaaaaawn.

A final bad Unity thingamajig is this innocent-looking thing here:

tip_a_day_04_02

It looks fine, but there’s one deceptively-demanding call here: GetComponent(). Behind the scenes, this sneaky little fucker is grabbing a whole list of components on your game object just to find your singular component, then sending the list to our good ‘ol friend, the garbage collector. It’s best if you can avoid use where possible, or at least limit use to Start(). One good design tip is to have a sort-of ‘manager’ in your scene that, at the start, you send references of objects to without using GetComponent() – for example, from my PlayerController class, I send my GameManager a reference to the PlayerController for anyone to access. Then whenever I need to reference PlayerController, I can find it through GameManager rather than using GetComponent() all over the shop. It’s also far more elegant, since I know where I can find all the references I’ll need.

Java Programming: The health system and changing levels!

Hey, I am back again, and it’s been a busy week or two in Java for me! I’ve done a bit of optimising of the player rendering, and I’ve added a few more tiles, but the standout features in this new update are the new health system, which is almost fully implemented, and the ability to change between levels by standing on a ‘warp’ block! I have also started to add an experience system, but this is barely implemented yet, so take no notice of that. The changelist for this update is:

  • Almost fully-implemented health system. The health of the player cannot exceed 100 and if it reaches 0, the game will cease to continue and “You died!” is displayed on the screen.
  • The new Spikes tile will harm you on 1/60 ticks (once a second)
  • The lava tile will now harm the player at an extremely fast rate
  • Lava will now set the player on fire. The player will continue to be on fire after exiting the lava for a short while. Entering water or a heal tile (new in this update) will extinguish the fire.
  • The new heal tile simply heals any player stood on it.
  • A new marble tile, the texture of which is temporary, is currently a solid tile and is purely decorative.
  • Swimming in water too long (10 seconds) will cause you to run out of air and start taking damage to imitate drowning.
  • New level warp tile. When you stand on this tile, it will transport you to a new level, and you will keep all of your health (and experience) you have obtained. The level you warp to is currently linear, in that it is coded straight into the source code, and no user input can change the target level. In the future, these tiles will be positioned on the edge of the map for linear gameplay, similar to the original Legend of Zelda, and a new tile will be added for user-controlled warping, for sandbox gameplay.
  • The game icon is now a little version of the player (aww, cute!)
  • The number of frames and ticks the game is currently running at are displayed in the game’s title.

Now you know what’s been changed, screenshot time!Image

This shows the new game screen, with the (out of date, sorry) version number at the bottom and the health counter at the top; this will eventually be changed into a more graphical display. The purple tiles near the player are the new warp tiles, just walk on these and in an instant, this happens:

Image

…and as if by magic, the player is transported to the next level! The health stays the same across levels. The warp tiles for this level are in the top-left corner, but within the n-shaped marble structure you can see are some heal tiles. Standing on them causes the player to turn purple for a short while and will heal 5% health every second. There is also a singular heal tile to the left of this.

[EDIT:] I can’t believe I forgot about the dark grey tiles on the left! Silly me. They are spike tiles, and they hurt the player when they walk on it.

Image

The counter below the health shows the player’s air while swimming, when it reaches 0 it displays “No air!” in red and the player will start being hurt.

Image

This shows the death screen, which will be much improved in the future, as well as the player in lava and on fire (shows the effect that the player turns red while hurt also). At this point, the game will continue to render and tick but the player cannot move due to the input being disabled.

That’s that for today’s update, sometime in the future I hope to put out an early test release for this game so that you can try it out and give feedback on bugs, features you would like etc. but this will only happen when this turns into an actual game, right now all you can do is move about really, but considering this is my first game, it’s going very well! Some features I will attempt to add soon are items, more entities (such as mob spawners, maybe arrows) and therefore more mobs, perhaps some hostile ones, and more levels with some linear gameplay. Also coming soon (maybe), I will review a few random games I got my hands on recently, including some really old favourites of mine, as well as some new games I’ve never played before. I will probably review around 10 games, depending on the time I have available. As always, thanks for reading and stick around for more soon.

-Daniel

Java Programming: Some progress has been made!

Sorry I’ve been gone for so long, I’ve been busy with other things. On the upside, I did learn a lot more about Java programming, and I’m here to show my progress so far on a little practice game I am making. So anyway, screenshot time:

Image

So here, you can see the whole game window and most of what I’ve got working so far. Firstly, it’s a 2.5D, or top-down, game, similar to how the original Zelda games were. You can see mostly grass with some red and yellow flowers (the flowers move slowly around as if there’s a breeze),  with some stone on the right. You can’t walk into the stone, as the player (the blue guy in the centre) has collision detection, and the stone itself is a solid tile, meaning it will prevent the player entering that tile when a collision between the two happens. You can also see a cat near the player, which was just a little test to see if I could implement an extra mob and animate it properly, which turned out successful. The cat doesn’t have an AI but I will try to get one working sometime. The screen you can see is only a portion of a larger level, as the screen moves around the player as he moves. Another thing in the game is water:

Image

The water flows in waves towards the top-right of the screen, and ripples form around the player, but unfortunately you can’t see the animations here. The player sinks down slightly when entering water and his lower body disappears, so that it looks like he is swimming.

The game is not yet randomly generated, instead each tile is designated its own ‘colour’, and a .png file must be used with one pixel representing an in-game tile. Each pixel is read from the file, and the colour of each pixel will generate the in-game tile equivalent (for example, a specific mid-green-coloured pixel in the .png file will generate one grass tile, one light grey pixel will generate one stone tile, and so on). This may be an inefficient way of generation, but it allows for easier customisation. In the future the method of loading may use a data file instead, and the generation will be randomly-generated by the code.

That’s my progress so far, I hope you’re more interested as a result of reading this, and if there’s anything you want me to implement, just leave a comment and I will try adding/ improving what’s here.

Image

I’ve been following a VERY helpful YouTube series on Java game development, this guy is amazing, and if you’re interested in learning how to do what I’ve done here, just follow this series, it’s extremely helpful. Here is the first video in the series: http://www.youtube.com/watch?v=VE7ezYCTPe4

Good luck to everyone who’s thinking of trying out Java game development, and thanks for the support.

-Daniel

An introduction

Hey people, this blog will be full of game reviews and the progress I am making on my own game. Since I play so many video games, I decided to make my own with all the ideas I’ve accumulated, so I’ve started learning the Java programming language. I will be showing my progress here, and also maybe help you if it’s possible (I’m only starting out with Java, but I’m hoping to get better, so maybe in the future I will have my own YouTube series showing people how to make simple games).

The games I play include the likes of Minecraft (awesome game by Mojang, if you haven’t played it, why not? Get it now), Mario, Pokemon and generally stuff by Nintendo (the only current-gen console I own is a 3DS, and it’s not a real console), but like everyone else, I have played games like Call of Duty and Halo. So if I find any games worthy of review, I’ll review them. So stick around and have fun reading!

-Daniel