Table of ContentsThe ActorsCollision Detection

Input Handling

Watching those cars and trucks cruising along is very entertaining, I knowI could just watch it for hours. The real action, however, is in accepting the challenge of navigating your little wombat across the road without turning it into a photo opportunity for roadkill.com. To do this, you need to get some input from the player and translate that into movement.

Guiding your wombat requires reading and reacting to input from the MID. You can do this by adding a keyPressed event handler to the GameScreen class.

/**
 * Called when a key is pressed. Based on which key they hit it moves the
 * WombatActor.
 * @param keyCode The key that was pressed.
 */
protected void keyPressed(int keyCode)
{
   switch (getGameAction(keyCode))
   {
      case UP:
         wombat.setY(wombat.getY() - laneHeight);
         break;
      case DOWN:
         wombat.setY(wombat.getY() + laneHeight);
         break; 
      case RIGHT:
         wombat.setX(wombat.getX() + laneHeight);
         break;
      case LEFT:
         wombat.setX(wombat.getX() - laneHeight);
         break;
   }
}

Inside this method, you interpret the key that was struck and move the wombat the appropriate distance along either the x- or y-axis. The setX method in the wombat class will take care of limiting the movement to the screen boundaries.

    Table of ContentsThe ActorsCollision Detection