简体   繁体   中英

XNA C# Issue with Keyboard Array

I've started making a Player class for my game, so due to the amount of controls for the game I used the Key's array into a switch to make it simple. It works properly with all keys except for one.

When I press Space Bar and The Arrow Keys, it only detects one of the arrow keys and the space bar at the same time. But it only occurs with the space bar. I was trying to solve this but I commented the space part and it does the same.

It doesn't happen if i use the isDown method.

Here is the code:

for (int Key = 0; Key < Keyboard.GetState().GetPressedKeys().Count(); Key++)
{
    switch (Keyboard.GetState().GetPressedKeys()[Key])
    {
        case Keys.Up:
            Move(Direction.Up);
            Console.WriteLine("Up");
            break;
        case Keys.Down:
            Move(Direction.Down);
            Console.WriteLine("Down");
            break;
        case Keys.Left:
            Move(Direction.Left);
            Console.WriteLine("Left");
            break;
        case Keys.Right:
            Move(Direction.Right);
            Console.WriteLine("Right");
            break;
        case Keys.LeftShift:
            if (!isShifting)
                isShifting = true;
            break;
        case Keys.A:
            if (!oldKeyboardState.IsKeyDown(Keys.A))
                CastSkill(1);
            break;
        case Keys.Space:
            shootMgr.Shoot();
            break;
    }
}

I would personally do it in ifs instead of your for and switch.

var keys = Keyboard.GetState();

if (keys.IsKeyDown(Keys.Up) {
    Move(Direction.Up);
    Console.WriteLine("Up");
}
if (keys.IsKeyDown(Keys.Down) {
    ...
}

But if you wanted to do it with a loop and switch, what happens when you switch it around to:

var keys = Keyboard.GetState().GetPressedKeys();
for (var i = 0; i < keys.Count(); i++) {
    switch (keys[i]) {
        case: Keys.Up:
            ...
            break;
        case: Keys.Down:
            ...
            break;
    }
}

I believe your problem is coming from calling and receiving a new array from GetPressedKeys() each iteration of your loop.

How many keys do u press at the same time. If you are pressing to many at the same time u will get 'Keyboard ghosting': http://www.microsoft.com/appliedsciences/antighostingexplained.mspx

Now if that's not the case, I would like to see what your Move(Direction.Up) does.

I would personally not use a for switch but:

if (Keyboard.GetState().IsKeyDown(Keys.D))
{
     velocity.Y = 0f;
     velocity.X = 2f;                
}

Put this is in the update from your Player class(in case you didn't know :S)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM