views:

247

answers:

2

Hi,

    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
            if (e.KeyCode == Keys.W)
                player1.moveUp();
            if (e.KeyCode == Keys.NumPad8)
                player2.moveUp();
    }

In the above code the moveUp methods basically just increment a value. I want it so both keys can be pressed (or held down)at the same time and both events will trigger. Thanks, Nevik

+4  A: 

Get the state of the keyboard and check for the status of the keys that you want.

Events are not the best way to go in gaming. You need faster response.

[DllImport("user32.dll")]
public static extern int GetKeyboardState(byte [] lpKeyState);
...
byte[] bCharData = new byte[256];
GetKeyboardState(bCharData);


Another way, taken from here,

[DllImport("user32.dll")]
static extern short GetKeyState(VirtualKeyStates nVirtKey);
...
public static bool IsKeyPressed(VirtualKeyStates testKey)
{
    bool keyPressed = false;
    short result= GetKeyState(testKey);

    switch (result)
    {
        case 0:
            // Not pressed and not toggled on.
            keyPressed = false;
            break;

        case 1:
            // Not pressed, but toggled on
            keyPressed = false;
            break;

        default:
            // Pressed (and may be toggled on)
            keyPressed = true;
            break;
    }

    return keyPressed;
}


More links.

Basically, these are already available on net. Try searching before asking. It will be faster :)

Nayan
+1 This is correct, events are too slow for games, if you take care of the keystate in your "game loop" it will be both faster and much more responsive
masenkablast
+1  A: 

Let's assume you have a "game loop" that updates the object you're moving with the keyboard. The KeyDown event should change the object state to "moving upwards". And your loop then gives it new positions each time it runs.

The KeyUp event should change the state back to "idle". Iff the state is still "moving upwards".

You now no longer depend on a keystroke repeating to keep the object moving. And will have no trouble with the player pressing multiple keys at the same time.

Hans Passant