Sign in to follow this  
ChristianFrantz

xna keyboard issues

Recommended Posts

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?

Share this post


Link to post
Share on other sites
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.

Edited by Andy474

Share this post


Link to post
Share on other sites

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 :)

Share this post


Link to post
Share on other sites

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!!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this