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.

if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
{
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
Mix_HaltMusic();

// Free up the memory for the music
Mix_FreeMusic(music);

// Free up any memory for the sfx
Mix_FreeChunk(chunk);

// Close our audio device
Mix_CloseAudio();

SDL_Quit();
}

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

Wednesday, July 4, 2007

NeHe Lesson 20: Masking

Puuh! Full 20 lessons now. =) Almost half of them. With luck I'll get them all by the end of the year. ;)

This lesson doesn't bring anything special on the D-table, but the lesson itself is interesting, so go read it.

I separated the texture loading into two functions, because there is 5 different textures which need to be loaded.

The source can be found here.