开发者

Multiple key presses doing different events in C#

开发者 https://www.devze.com 2022-12-28 05:00 出处:网络
private void Form1_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.W) player1.moveUp(); if (e.KeyCode == Keys.NumPad8)

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开发者_Go百科 both events will trigger. Thanks, Nevik


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消