The Update Loop, Input and You!

This tutorial will cover the basic game loop and handling keyboard inputs.

Start Your Engines!

Creating the Update function is identical to the Render function from before. But as we do that, lets also create an Engine class.

public class Engine
{
    private RLRootConsole rootConsole;
    public Engine(RLRootConsole console)
    {
        rootConsole = console;
        rootConsole.Render += Render;
        rootConsole.Update += Update;
    }

    public void Render(object sender, UpdateEventArgs e)
    {
    }

    public void Update(object sender, UpdateEventArgs e)
    {
    }
}

This simplifies things in our Main function

rootConsole = new RLRootConsole("ascii_8x8.png", 60, 40, 8, 8);
engine = new Engine(rootConsole);
rootConsole.Run();
Where you @?

Now we let’s create our player. Right now we just need to track where the player is and draw it.

private int playerX;
private int playerY;

public void Render(object sender, UpdateEventArgs e)
{
    rootConsole.Clear();
    rootConsole.Set(playerX, playerY, RLColor.White, null, '@');
    rootConsole.Draw();
}

Ah, but it wouldn’t be a game without interaction, time to add Update code.

public void Update(object sender, UpdateEventArgs e)
{
    RLKeyPress keyPress = rootConsole.Keyboard.GetKeyPress();
    if (keyPress != null)
    {
        switch (keyPress.Key)
        {
            case RLKey.Up: playerY--; break;
            case RLKey.Down: playerY++; break;
            case RLKey.Left: playerX--; break;
            case RLKey.Right: playerX++; break;
        }
    }
}

Compile and run, to run around.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s