Val
Val

Reputation: 57

How would I compress keyboard input, if statements into a for loop? (shooting bullets)

so I'm creating an XNA game, that consists of a spaceship, shooting bullets around, at different enemy spaceships that carry around "strings". It's essentially a spelling game, where I have to spell out the word by hitting the spaceships with the right letters.

Anyway, my problem is that, I've currently got two "if" statements in order of shooting a bullet, and it'd be some horrible programming if I did this for the rest of the 25 letter keys on the keyboard. Yes, I do need every single "letter" key on the keyboard, as it will be a spelling game. Here is an example of code I've got for one of the bullets.

What I'm essentially doing here is if "Fired" boolean is false, and the appropriate key is pressed, I am positioning a rectangle in the position of the gun and setting "Fired" to true, to let the bullet loose. An then obviously whenever it hits the top of the screen, I set the fired back to false, in order of a reloading concept.

 if (MyKeys.IsKeyDown(Keys.Q) && OldKeys.IsKeyUp(Keys.Q) && Fired[0] == false)
        {

            CurrentChar = "Q";
            Shot[0].X = SpaceStationGun.X;
            Shot[0].Y = SpaceStationGun.Y;
            Fired[0] = true;
        }

        if (Fired[0] == true)
        {
            Shot[0].Y -= SHOT_SPEED;
            if (Shot[0].Y < 0 - SHOT_HEIGHT)
            {
                Fired[0] = false;
            }
        }

Now the question is, how would I loop this for the rest of the 25 letter keys on the keyboard, and still hold the functionality?

Upvotes: 0

Views: 61

Answers (1)

Lockdowne
Lockdowne

Reputation: 484

Keyboard.GetState().GetPressedKeys() gives you a collection of Keys that were pressed during the duration of its state.

I do not see how your MyKeys and OldKeys are being updated but I will assume you can use the following

var keysPressed = MyKeys.GetPressedKeys()
    .Where(k => !OldKeys.GetPressedKeys().Contains(k));

foreach(var key in keysPressed)
{
    // Do your logic
}

OldKeys = MyKeys;

MyKeys = Keyboard.GetState();

Upvotes: 0

Related Questions