I'm making a pacman game and at the moment my pacman is moving within the allowed coordinates of the map when I press the right, left, up or down arrow key. It is only moving when I hold the key down. I was wondering how I could do this so that he moves automatically on the key press until he hits the wall in the map, so that I don't need to hold the arrow down.
This is
if (e.KeyCode == Keys.Down)
{
if (coordinates[(pac.xPosition + 16) / 20, (pac.yPosition + 20) / 20].CellType == 'o'
|| coordinates[(pac.xPosition + 16) / 20, (pac.yPosition + 20) / 20].CellType == 'd'
|| coordinates[(pac.xPosition + 16) / 20, (pac.yPosition + 20) / 20].CellType == 'p')
{
pac.setPacmanImage();
pac.setPacmanImageDown(currentMouthPosition);
checkBounds();
}
The cell types o, p and d are the only cells he is allowed to move on within the map. These cells are being drawn within a textfile.
Sorry if it is hard to understand what I am asking but I am sure it is a fairly simple explanation.
Thank you in advance.
Instead of moving Pac-Man during the keypress, use the keypress to set a direction, and move Pac-Man outside the keypress logic.
enum Direction {Stopped, Left, Right, Up, Down};
Direction current_dir = Direction.Stopped;
// Check keypress for direction change.
if (e.KeyCode == Keys.Down) {
current_dir = Direction.Down;
} else if (e.KeyCode == Keys.Up) {
current_dir = Direction.Up;
} else if (e.KeyCode == Keys.Left) {
current_dir = Direction.Left;
} else if (e.KeyCode == Keys.Right) {
current_dir = Direction.Right;
}
// Depending on direction, move Pac-Man.
if (current_dir == Direction.Up) {
// Move Pac-Man up
} else if (current_dir == Direction.Down) {
// Move Pac-Man down
} else if (current_dir == Direction.Left) {
// Move Pac-Man left
} else if (current_dir == Direction.Right) {
// You get the picture..
}
As BartoszKP's comment recommends, you will want to set the direction in Pac-Man's private variables.