Quantcast
Channel: Game – Dark Views
Viewing all articles
Browse latest Browse all 22

Writing Games with Processing: Moving Around

$
0
0

The game would be pretty boring if Platty would just sit there, waiting to be eaten. The player needs to be able to move him around:

void keyPressed() {
  if(key == CODED) {
    if(keyCode == UP) {
      movePlayer(0, -1);
    } else if(keyCode == DOWN) {
      movePlayer(0, 1);
    } else if(keyCode == LEFT) {
      movePlayer(-1, 0);
    } else if(keyCode == RIGHT) {
      movePlayer(1, 0);
    }
  } else if(key == ' ') {
    movePlayer(0, 0);
  }  
}

As you can see, I’m using the cursor keys to move the character. You could as easily use the keys WASD or any other combination but since we don’t need the mouse, the cursor keys felt like a good choice. Also note that the player can sit around and wait using the space bar.

The code to move the character is pretty simple:

void movePlayer(int dx, int dy) {
  px += dx * tileSize;
  py += dy * tileSize;
}

An alternative would be to always center the screen around the character and move everything else.

Or you can try to move the player one pixel at a time. Change the code to

void movePlayer(int dx, int dy) {
  px += dx;
  py += dy;
}

and play a bit. How does that feel?

When playing with the game, you might notice a slight problem: You can move outside of the visible screen. We need to check that the new coordinate is valid before moving the character:

void movePlayer(int dx, int dy) {
  dx *= tileSize;
  dy *= tileSize;
  
  int newX = px + dx;
  int newY = py + dy;
  if(newX >= 0
    && newX < width
    && newY >= 0
    && newY < height
  ) {
    px = newX;
    py = newY;
  }
}

Nice. We have a player character, we have control, we have enemies. What else do we need? Moving the enemies.

You can find the whole source code here.

Previous: Enemies
First post: Getting Started


Tagged: Game, Games, Processing

Viewing all articles
Browse latest Browse all 22

Trending Articles