Tuesday, July 24, 2007

NeHe Lesson 21: Lines, Antialiasing, Timing, Ortho View And Simple Sounds

It's time for a new lesson. This time NeHe has made a simple game for us to enjoy.

First before doing anything else make sure that you have SDL_Mixer installed on your system, as we're going to use it to play back the music and sound effects.

Next is a small improvement I made over the C version, is the use of the enemies-array. The original lesson uses it as a static array, but I made it dynamic. This way we can use the D's great foreach-loop to go over every enemy in the level.

/// Enemy Information
GameObject[] enemies;


* Resets the player character and all the enemies.
void resetObjects()
player.x = 0; // Reset Player X Position To Far Left Of The Screen
player.y = 0; // Reset Player Y Position To The Top Of The Screen
player.fx = 0; // Set Fine X Position To Match
player.fy = 0; // Set Fine Y Position To Match

// Create the enemies for the next level/stage
enemies = new GameObject[stage * level];
// Loop Through All The Enemies
foreach (inout enemy ; enemies)
// A Random X Position
enemy.x = 5 + rand.next() % 6;
// A Random Y Position
enemy.y = rand.next() % 11;
// Set Fine X To Match
enemy.fx = enemy.x * 60;
// Set Fine Y To Match
enemy.fy = enemy.y * 40;

As you can see there, we use the new operator to create just the number of enemies for the level/stage. Then we can loop over the array with foreach and be certain that we always have the correct number of enemies.

In the module constructor the parameter to SDL_Init has changed to SDL_INIT_EVERYTHING.

throw new Exception("Failed to initialize SDL: " ~ getSDLError());

This is needed for audio. There are other options, which you can read about here.

The module destructor is responsible for freeing the textures and SDL_Mixer's buffers.

static ~this()
// Clean up our font list
glDeleteLists(base, 256);

// Clean up our textures
glDeleteTextures(NUM_TEXTURES, &textures[0]);

// Stop playing the music

// Free up the memory for the music

// Free up any memory for the sfx

// Close our audio device


That's about it. Everything else is hopefully easy enough to understand, so just dig in.