Arvin Ashrafi
Arvin Ashrafi

Reputation: 671

C# - Shoot only once - IsKeyUp & IsKeyDown

I have been a problem with my Shoot Em Up game for a while now and I really can't seem to find any answers. I want to only shoot 1 bullet even though I'm holding down the spacebar. With my current code I don't fire any bullets at all. What am I doing wrong?

        KeyboardState newState = Keyboard.GetState();
        KeyboardState oldState = Keyboard.GetState();

        if (oldState.IsKeyUp(Keys.Space) && newState.IsKeyDown(Keys.Space))
        {
            bulletList.Add(new Bullet(content.Load<Texture2D>(@"bullet"), new Vector2(initialPos.X, initialPos.Y - 28), new Vector2(2, 4), spriteBatch));
        }

        oldState = newState;

Upvotes: 0

Views: 639

Answers (3)

davidsbro
davidsbro

Reputation: 2758

Your problem is that you are checking to see if the spacebar is both up and down, which is impossible. I think you should try something like this:

bool readytofire = true;
public override void Update()
{
    KeyboardState newState = Keyboard.GetState();

    readytofire = !newState.IsKeyDown(Keys.Space);

    if (newState.IsKeyDown(Keys.Space) && readytofire)
    {
        bulletList.Add(new Bullet(content.Load<Texture2D>(@"bullet"), new Vector2(initialPos.X, initialPos.Y - 28), new Vector2(2, 4), spriteBatch));
    }
}

Upvotes: 1

mcsilvio
mcsilvio

Reputation: 1098

KeyboardState newState = Keyboard.GetState();
KeyboardState oldState = Keyboard.GetState();

These will have the same value.

if (oldState.IsKeyUp(Keys.Space) && newState.IsKeyDown(Keys.Space))

This is checking that the Space key is both UP and DOWN.

Both code fragments don't make sense. Is this code inside a loop? If so, check for space DOWN and use a boolean flag to make sure you fire only once. Then check for space UP, reversing the flag.

Upvotes: 0

MikeH
MikeH

Reputation: 4395

You're setting the old state right before checking it, so it will always be the same as newState. Remove this line: KeyboardState oldState = Keyboard.GetState();

You may need to assign a value to oldState for the first time it runs through your loop.

Upvotes: 0

Related Questions