6
UNDER THE SCOPE: BUILD YOUR OWN USB MICROSCOPE FOR £15 Torturing webcams so you don’t have to... Issue 227 June 2009 £5.99 Outside UK & ROI £6.49 Empire Total War guide FALLOUT 3 THE PIT: DIGGING DEEPER COMPANY OF HEROES TALES OF VALOR 61 Games 90 Apps See page 118 FREE PERFORMANCE GEAR & GAMING VISTA VS XP VS WINDOWS 7 THE DEFINITIVE BENCHMARKS IS IT TIME TO CONSIDER LINUX? INSTANT BOOTING AND GAMING HERE’S TO SWIMMING WITH BOW LEGGED WOMEN WWW.PCFORMAT.CO.UK ISSUE 227 JUNE 2009 THERE’S MORE… Big screens from £140 AMD’s budget super-computer Game coding: Explosions ISSUE 227 HERE’S TO SWIMMING WITH BOW LEGGED WOMEN Nvidia GTX275 versus AMD HD 4890

Become a coder Part 5

Embed Size (px)

DESCRIPTION

There are lots of things you could be doing while waiting for Diablo 3 to be released, but most of them are rubbish. Watching TV is for lackadaisical layabouts. Going shopping with your significant other usually results in you being dragged unwillingly out of every games shop on the high street. In fact, it’s easy to get so bored that you’re considering signing up to Twitter to see if you can organise a flash mob at your house just so you can meet some new people. Stop! Before you type ‘twitter.com’ into your web browser, may I remind you that your computer is capable of doing so much more than providing you with reams of angst-ridden moaning from internet nobodies? Yes, that’s right: a great way to fill up your time and have fun is to open the door to the dark cesspit of your soul and vent your strangely evil ideas into your own computer programs.

Citation preview

Page 1: Become a coder Part 5

UNDER THE SCOPE: BUILD YOUR OWN USB MICROSCOPE FOR £15

Torturing webcams so you don’t have to...

Issue 227 June 2009 £5.99 Outside UK & ROI £6.49

Empire Total War

guide

FALLOUT 3 THE PIT: DIGGING DEEPER

COMPANY OF HEROESTALES OF VALOR

61 Games90 AppsSee page 118

FREE

PERFORMANCE GEAR & GAMING

VISTA VS XP VS WINDOWS 7THE DEFINITIVE BENCHMARKS

IS IT TIME TO CONSIDER LINUX?INSTANT BOOTING AND GAMING

HER

E’S TO SW

IMM

ING

WITH

BOW

LEGG

ED W

OM

EN

WW

W.PCFO

RM

AT.CO.U

KISSU

E 227JU

NE 2009

THERE’S MORE…Big screens from £140AMD’s budget super-computerGame coding: Explosions

ISSUE 227 HERE’S TO SWIMMING WITH BOW LEGGED WOMEN

Nvidia GTX275 versus AMD HD 4890

PCF227.cover 1 15/4/09 3:17:54 pm

Page 2: Become a coder Part 5

Game coding

Become a game coder

Have you watched all of this year’s GDC announcements and rated them a resounding meh out of 10? Why not take on the world with your own dazzling genius – now with added special effects!

end. And don’t pretend that you were planning to make some super-clever brainiac game to teach your kids stuff. Deep down, you want to make a game called ‘Blast Zombies Into a Big Bloody Mess’ and you know it.

This is the last instalment of our games coding series, but before I bid you adieu, I want to show off a simple special effect that will transform your game into something that looks cooler. Because, sad as it is, special effects are often what transform a good game into a good game that sells really well. It won’t make your game any better at its core, but it’ll make really shallow people (ie, most people) like it more and it’s nice to be loved, right? Right.

But fi rst up, I want to check you’ve done your homework, rather than smoking behind the bike sheds…

Light-speed homeworkNormally, I call the homework ‘Fun’, ‘Tricky’, ‘Taxing’ and ‘Nightmare’, largely because I get a kick when people recognise old game references (lips, ice

There are lots of things you could be doing while waiting for Diablo 3 to be released, but most of them are rubbish.

Watching TV is for lackadaisical layabouts. Going shopping with your signifi cant other usually results in you being dragged unwillingly out of every games shop on the high street. In fact, it’s easy to get so bored that you’re considering signing up to Twitter to see if you can organise a fl ash mob at your house just so you can meet some new people.

Stop! Before you type ‘twitter.com’ into your web browser, may I remind you that your computer is capable of doing so much more than providing you with reams of angst-ridden moaning from internet nobodies? Yes, that’s right: a great way to fi ll up your time and have fun is to open the door to the dark cesspit of your soul and vent your strangely evil ideas into your own computer programs. More specifi cally, your own computer games, because that way you get to shoot things at the

cream, violin, earth, snowman, anyone?). But last issue the homework was all fairly easy, so I hope you managed to get it all done.

Let’s start at the top by making the ‘empty’ and ‘explode’ sounds vary in pitch. To do that, browse to the Content\Audio directory and open GameAudio.xap. When XACT opens your Sound Bank, choose ‘empty’ from the top pane, then look down in the bottom left of the screen for the group box called ‘Pitch Variation’ and make sure ‘Enable’ is checked. Do the same for ‘explode’ and the Fun homework assignment is done.

The Tricky homework was to only show the score and laser recharge information when the Right Trigger is held down. Hopefully you read last issue’s Reading Buttons box, which pointed you towards two important things: 1) state.IsButtonDown() and 2) typing ‘Buttons’ followed by a full stop will show a list of buttons you can read.

To complete this homework, look down to your Draw() method for the line

Above The fi nished product, now with added explosions

70 June 2009

PCF227.prog 70 17/4/09 13:33:17

Page 3: Become a coder Part 5

Game coding

that begins ‘Color col = Color.Lerp’, because those three lines there are what control the status being drawn to the screen. To make that status appear only when Right Trigger is held down, we need to put those lines inside an ‘if’ statement, like this:

if (GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.RightTrigger)) { Color col = Color.Lerp(Color.Red, Color.Green, LaserRecharge / 1000.0f); spriteBatch.DrawString(fntMain, “Power: “ + LaserRecharge, new Vector2(30, 30), col); spriteBatch.DrawString(fntMain, “Score: “ + Score, new Vector2(30, 70), Color.White);}

The Taxing homework assignment was to make pressing the ‘A’ button on the controller fi re a shot in four directions – it should use 400 energy and should only be possible if the player has at least 900 energy remaining. Okay, if you’re thinking this task is anything but easy, you’re dead wrong. Seriously, all you need to do here is call FireLaser() four times after checking to make sure that LaserRecharge is greater or equal to 900. Putting this code at the end of the CheckForFiring() method should do the trick:

if (state.IsButtonDown(Buttons.A)) { if (LaserRecharge >= 900) { FireLaser(-1, -1); FireLaser(1, -1); FireLaser(-1, 1); FireLaser(1, 1); }}

That will cause the player to fi re in all four diagonal directions, which I think is more visually pleasing than fi ring in the more traditional NSEW directions.

And now we’re just left with the Nightmare task, which was the single remotely tricky piece of homework – and only because it required several simple changes rather than just one. The goal is to make the ‘B’ button change weapons to a gun that fi res very slowly but doesn’t stop when it destroys an asteroid – it just carries on moving, so it can destroy multiple asteroids.

To do this, you need to make the following changes:

1 Make ‘B’ change weapons. We’ll do this by reading IsButtonDown(), but we need to be careful not to change the weapon more than once when a player taps ‘B’ quickly.

2 Store the type of weapon that was used inside each laser, so that it can

“SPECIAL EFFECTS CAN TRANSFORM A GOOD GAME INTO A GOOD GAME THAT SELLS REALLY WELL”

On memoryI couldn’t possibly fi nish this short series on game coding without at least mentioning the signifi cance of memory. You see, the thing about .NET coding is that it allows you to be incredibly lazy and, for the most part, you can get away with it. The problem is that, when your game starts pushing the hardware more, memory becomes tighter and you need to be more careful with what you do with it.

By default, .NET tracks all the memory you allocate and will attempt to automatically clean up after you whenever you fi nish using something. The problem with this arises when you’ve fi nished using something but .NET doesn’t realise it. This results in what programers call a memory leak – memory that can’t be reclaimed and is essentially just being wasted.

An obvious example of a memory leak in our code is in the new particle system code. We create particle systems and add them to an array, but we never remove them once they’ve fi nished. That means that any memory allocated by that particle system (which admittedly isn’t very much – it cleans up after itself pretty well) is left allocated but not really used.

The solution to memory leaks is to be more vigilant about your memory use. In the particle system example, the Update() method returns false when the particle system is fi nished, so in your Game1.cs fi le, you should try checking the return value of Update() to see whether the particle system can be removed from the Explosions array.

Left Extra controls such as a four-way fi re system make the game more fun

RAM: your development PC probably has at least 2GB of it, but the Xbox 360 has just 512MB

June 2009 71

PCF227.prog 71 17/4/09 13:33:20

Page 4: Become a coder Part 5

Game codingGame coding

respond the right way if the player changes weapons again after fi ring.

3 Put in the logic required to leave the laser alone when it collides with an asteroid if it’s one of the super lasers.

Scroll up to near the top of Game1.cs and put this directly beneath the line ‘int LaserRecharge = 100;’:

bool IsSuperLaser;

A ‘bool’ stores either ‘true’ or ‘false’, with ‘false’ being the default – perfect

for our needs. When ‘B’ is pressed, we need to tell XNA to set IsSuperLaser to be the opposite of whatever it is right now. We also need to make sure that XNA doesn’t think we’re pressing ‘B’ multiple times when really we’re just tapping the button. This is quite common because XNA updates the game 60 times a second, so if your button press lasts longer than that it will be registered multiple times.

The best place to switch weapons is inside CheckForFiring, because we’re already working with button states in

public Cue sndLaser;

Then put this line of code directly beneath it:

public bool IsSuperLaser;

That allocates a little bit of RAM, where we’ll be storing the laser type. To actually set it, just put this line of code into FireLaser(), just before ‘Lasers.Add(laser);’:

laser.IsSuperLaser = IsSuperLaser;

While you’re there, you can satisfy the requirement to make the super laser fi re more slowly by simply setting LastLaserFire to a point sometime in the future, as I did for checking whether or not ‘B’ was pressed. That whole section of code should therefore look like this:

laser.IsSuperLaser = IsSuperLaser;Lasers.Add(laser);if (IsSuperLaser) { LastLaserFire = Environment.TickCount + 500;} else { LastLaserFire = Environment.TickCount;}

If you want to make your super lasers stand out a little more in the game, simply add some colouration to them. For example, you could change your

there. Under the code we just added for the homework to check whether the ‘A’ button was being pressed, add this:

if (state.IsButtonDown(Buttons.B)) { IsSuperLaser = !IsSuperLaser; LastLaserFiRE=Environment.TickCount +500;}

The exclamation mark means ‘not’, which means the whole line read in English is ‘set IsSuperLaser to not IsSuperLaser’. This has the effect of making it the opposite to whatever it

already is. And then the sneaky bit: I’ve set LastLaserFire to be 500 milliseconds after the current time, which means the player can’t fi re or change weapons for half a second afterwards. Not only does that solve the problem of people holding down ‘B’ for more than 1/60th of a second, but it also gives a nice pause between changing weapons, making it a bit more of a tactical choice!

Step two requires us to remember which type of laser each one is. Open BangLaser.cs and look for this line:

“OPEN THE CESSPIT OF YOUR SOUL AND VENT YOUR EVIL IDEAS INTO YOUR OWN COMPUTER PROGRAMS”

Check out creators.xna.com/en-GB/sample/particle for an offi cial tutorial from Microsoft about how to make more advanced particle systems

72 June 2009

PCF227.prog 72 17/4/09 13:33:21

Page 5: Become a coder Part 5

Game codingGame coding

Draw() method to use this code for drawing lasers:

foreach (BangLaser laser in Lasers) { if (laser.IsSuperLaser) { spriteBatch.Draw(sfcLaser, laser.Position, null, Color.Red, 0.0f, new Vector2(12, 12), 1.0f, SpriteEffects.None, 0); } else { spriteBatch.Draw(sfcLaser, laser.Position, null, Color.White, 0.0f, new Vector2(12, 12), 1.0f, SpriteEffects.None, 0); }}

A simple colour change can make all the difference!

The fi nal assignment was to make the super lasers not disappear if they crash into asteroids. Look inside the CheckForCollisions() method and you’ll see the line Lasers.RemoveAt(i). Change that to this:

if (!laser.IsSuperLaser) { Lasers.RemoveAt(i);}

Again, the exclamation mark means ‘not’, so this means ‘if this laser isn’t a super laser, remove it when we collide with an asteroid’.

That’s it – homework done. Time for the super whizz bang special effects!

My god, it’s full of particles!Particle systems form the core of lots of special effects in modern games. But they also require lots of code, which is

very dull. I’ve taken the cheat’s way out and put together a simple particle system for you to use in your own projects. It’s designed to be easy to drop in and use, so please go ahead and use it as if it were your own work.

First, look on your PCF DVD for my example fi les for this issue. You need to copy the fi le ParticleSystem.cs into your

own project directory, then copy particle_smoke.tga from my Content directory into your own.

Now go back into VC# and choose Project > Add Existing Item, then select ParticleSystem.cs from your project directory. Now look in the Solution Explorer, right-click on Content, then choose Add > Existing Item and select the particle_smoke.tga fi le from your Content directory.

As with Asteroids and Lasers, we need to allocate RAM to store a list of the explosions, as well as to create space for the texture that will be used to draw smoke. To do that, take a look at the beginning of Game1.cs for the line that begins with ‘List<BangLaser> Lasers’ and add the following two lines:

List<PCFParticleSystem> Explosions = new List<PCFParticleSystem>();Texture2D sfcSmoke;

Scroll down to LoadContent(), which is where there are lots of lines like Content.Load<Texture2D>(whatever). Add this one to the end of that list to load the smoke texture into the game so that it can be used by our wonderful particle system:

sfcSmoke = Content.Load<Texture2D>(“particle_smoke”);

The next step is to tell the explosions to update themselves along with the rest of the game, so scroll down to your Update() method and add these lines just before UpdateUfo():

foreach (PCFParticleSystem explosion in Explosions) { explosion.Update(gameTime);}

The penultimate step is to actually draw the explosions. To do this go to the Draw() method and add the following lines just after the “foreach (BangAsteroid asteroid in Asteroids)” loop has fi nished:

foreach (PCFParticleSystem explosion in Explosions) { explosion.Draw(spriteBatch);}

Everything so far is just basic boilerplate code – you’ll need to put all

“YOU WANT TO MAKE A GAME CALLED ‘BLAST ZOMBIES INTO A BIG BLOODY MESS’ AND YOU KNOW IT”

Above The XNA Creators Club forums (creators.xna.com) may prove useful

This smoke particle is dull, so be creative and try other things – fi re, water, debris and

even bees are all perfect for particle systems

June 2009 73

PCF227.prog 73 17/4/09 13:33:21

Page 6: Become a coder Part 5

Game coding

that into whenever you want to use explosions in your games, regardless of how you want them to look. Now comes the fun part: creating the explosions! Particle systems are great because you can make them do all sorts of weird and wonderful things just by adding more and more variables to them. I’ve tried to keep my example particle system fairly simple, which means that the only variables you can set are the number, speed and colour of the particles, along with a couple of other variables for extra effects.

To create a basic explosion effect whenever an asteroid is destroyed, all you need to do is put this line of code directly after the call to Asteroids.RemoveAt(j) in CheckForCollisions():

Explosions.Add(new PCFParticleSystem(sfcSmoke, asteroid.Position, 200, 500, 75.0f, 300.0f, 2.0f, true, Color.White, Color.TransparentBlack));

Yes, that’s an absolute mess. Let me break it down for you:

− Add to the list of explosions a new particle system.

− Make it use sfcSmoke for its particle sprite.

− Start it at the asteroid position. − Give it 200 particles.

− Let the particles live for 500 milliseconds each.

− Make the minimum particle speed 75 units per second and the maximum 300.

− Give it two units of drag.− Make the particles increase in size

over time.− Set the starting colour to be white.− Set the fi nished colour to be

transparent black.

You can tinker with each of those to make your particle systems look different to mine. The beginning and end colours allow particles to fade away as they get older – the particle system automatically chooses a colour between the start colour and the end colour depending how far the particle is through its life.

The drag factor allows particles to slow down over time, so they can burst out really quickly then eventually slow down to a stop. Finally, making particles

grow over time will make them grow between 100 per cent and 200 per cent as they get older, which, for smoke, makes it look like the particle is dissipating. If you set ‘true’ to ‘false’, the particles will shrink instead.

Try the game now and you should be able to see the puff of smoke when asteroids are hit. But I encourage you to play around with the particle options. For example, try adding this line directly after the fi rst particle system line I just

gave you, creating a second particle system for each explosion:

Explosions.Add(new PCFParticleSystem(sfcSmoke, asteroid.Position, 100, 500, 75.0f, 200.0f, 2.0f, true, Color.DarkRed, new Color(139, 0, 0, 0)));

That one doesn’t move as fast and has a red colour, giving a bit more interest to the explosions.

And that’s it. There’s so much more I could teach you about games

programming (particularly particle systems) and about programming in general. I’m sure plenty of people will fl ame me for not going into more detail about memory management, for example! But the point is that I’ve given you a broad cognitive framework that will help you go out, hack around a bit and have some fun. After that, Google and message boards frequented by like-minded people are your best friends. Have fun! ¤ Paul Hudson

“PARTICLE SYSTEMS ARE GREAT – YOU CAN MAKE THEM DO ALL SORTS OF THINGS BY ADDING MORE VARIABLES”

Your homework is hereJust kidding – there’s no more homework this time because the game’s pretty much fi nished! Still, I’d like to think that you’ve learned enough from following this short tutorial series to want to try extending your game. The most obvious addition would be to make the player die whenever they crash into an asteroid, but you can spruce that up a little by adding a particularly large and interesting particle system.

Add a simple intro screen to your game to give it a more professional feel. Okay, maybe ‘professional’ is taking it a bit too far…

Here are some other ideas to try:

− Make asteroids drop power-ups that make your weapons more effective.− Add a simple starfi eld in the background. Each star is just a white dot moving along inside a List<BangStar> array, but make sure you

wrap stars around the screen when they hit the edge.− Allow a second player to take part if ‘GamePad.GetState(PlayerIndex.Two).IsConnected’ is set to true.− Add a simple introductory screen that displays before the game starts, showing off the title of your creation and, naturally, your own

name in fl ashing lights.

74 June 2009

PCF227.prog 74 17/4/09 13:33:22