im working on a simple game like “space invaders”,and i got into a problem.
Im trying to give the user, the possiblity to move as much as he want from Left to Right, and in the same time have the possiblty to shot using the “Space bar”.
My problem is: when i pressed more then 1 key, only 1 function run.
here a few stuff i tried:
-
Storing the keys in a
List<Keys>(but i didnt find any good way to excute the functions and everything become messy)2.normal handling of the key_down event like this:
protected void Form1_keysDown(object obj, KeyEventArgs e) { (e.KeyData == Keys.Space) spaceShip.FireBullets(); if (e.KeyCode == Keys.Left) spaceShip.MoveLeft(); if (e.KeyCode == Keys.Right) spaceShip.MoveRight(); }
my qustion is: what is a good way to make this work?
(sorry for my english)
You are relying on the keyboard controller repeating the key when you hold it down. That stops working when you press another key. This requires a different approach.
First you need an enum that indicates the motion state of the spaceship with values like NotMoving, MovingLeft and MovingRight. Add a variable of that type to your class. You’ll need both the KeyDown and KeyUp events. When you get a KeyDown for, say, Keys.Left then set the variable to MovingLeft. When you get the KeyUp event for Keys.Left then first check if the state variable is still MovingLeft and, if it is, change it NotMoving.
In your game loop, use the variable value to move the spaceship. Some sample code: