xna keyboard issues

Started by
2 comments, last by ChristianFrantz 11 years ago

I'm having trouble getting my keyboard to do what I want it to do.

this is at the top of my class


        KeyboardState currentKey;
        KeyboardState previousKey;

and this is in my update


currentKey = Keyboard.GetState();

            if (checkKey(Keys.Left))
            {
                ship.shipPos.X -= 4;
            }

            if (checkKey(Keys.Right))
            {
                ship.shipPos.X += 4;
            }

            if (checkKey(Keys.Space))
            {
                addBullet(bulletFirePos);
            }

            previousKey = currentKey;

this is the checkKey class


        public bool checkKey(Keys key)
        {
            return (currentKey.IsKeyDown(key) && previousKey.IsKeyUp(key));
        }

The bullets are shooting fine, one bullet every press of the spacebar...although when I shoot the first bullet it stays right in front of the ship and doesn't move...but thats not a keyboard issue lol. The problem I'm having is with moving left and right. I have to repeatedly press the key to get the ship to move and that's not what I want. How do I change the method so that if I just hold the key down the ship moves?

If you see a post from me, you can safely assume its C# and XNA :)

Advertisement

public bool IsKeyDown(Keys key)
{
    return (currentKey.IsKeyDown(key)); // this checks if it is down THIS frame
}
public bool IsNewKeyPress(Keys key)
{
    return (currentKey.IsKeyDown(key) && previousKey.IsKeyUp(key)); // this checks if it is down THIS frame and up LAST frame
}

So, your checkKey() function is checking if it is a new key press, E.g. down this frame up last frame, and so holding the key will only result in this event happening once. Hence, you have to press it multiple times.

As Andy said above, IsKeyDown is what you actually want in that scenario.

If your bullets aren't moving, you're probably not updating their position every frame :)

My Games -- My Music 

Come join us for some friendly game dev discussions over in XNA Chat!

the keyboard solution gave me worked. But it's just the very first bullet being created lol. As soon as I start the game and press space, it stays on the screen and doesnt move, but each bullet after that works fine!!

If you see a post from me, you can safely assume its C# and XNA :)

This topic is closed to new replies.

Advertisement