Blake O'Hare .com

Gamelight Tutorial: Part 2 - Getting User Input

In the last installment, I showed you how to set up a Silverlight project with a basic Gamelight game loop. The skeleton game only had an ugly pink background with a blue box that you could control by pressing the arrow keys. The way input was being retrieved from the user was by checking the current state of the arrow keys. The game ran at 30 frames per second. If the arrow key was pressed during the process-input phase of that frame, then the box would move. This is called polling. The other way to check for keyboard events is by checking for distinct events being fired. This alternate approach is ideal for things like firing a weapon or any other action that is a discrete event as opposed to something continuous (like movement).

The code for polling looked something like this:
if (Gamelight.Input.InputManager.IsKeyPressed(Gamelight.Input.Key.Left))
    this.x -= velocity;

Even though this code can technically go anywhere, it's best practice to put all Input checks in the ProcessInput method. The ProcessInput method also receives an array of InputEvents as its parameter. This is the list of events that have occurred between now and the last time ProcessInput was called.

Add the following code to the ProcessInput method:
foreach (Gamelight.Input.InputEvent ev in events)
    if (ev.Type == Gamelight.Input.EventType.KeyDown &&
        ev.Key == Gamelight.Input.Key.Space)
        this.is_blue = !this.is_blue;

And add the following field to the class:
private bool is_blue = true;

And modify the Render code so that is_blue is used to determine the color:
        ? Gamelight.Graphics.Colors.Blue
        : Gamelight.Graphics.Colors.Green,
    this.x % screenWidth, this.y % screenHeight, 30, 30);

Run the app now, and you'll see that the color toggles between blue and green each time you press the spacebar.

The other input method is of course the mouse.

The Chase

Add the following code to the for loop that checks the events:
if (ev.Type == Gamelight.Input.EventType.MouseMove)
    int mouse_x = ev.X;
    int mouse_y = ev.Y;

    this.x = (this.x * 15 + mouse_x) / 16;
    this.y = (this.y * 15 + mouse_y) / 16;

Every time you move the mouse, this code will move the square closer to the cursor. But of course, when you stop moving, the square will also stop moving. Simple enough.

A full list of all event types are:
  • KeyDown
  • KeyUp
  • MouseDown
  • MouseEnter
  • MouseLeave
  • MouseMove
  • MouseUp

Both keyboard events will always have the Key property set and all mouse events will have a coordinate set, and (if applicable) a Button property set to distinguish the left and right mouse buttons.

And I was about to post a screenshot of the outcome, but of course, as a PNG, it looks identical to the last picture I posted.

Next lesson: Loading Images