开发者

Processing key presses in C#

I'm making a game, and I have a class called MainCharacter that first initializes the main character (in a pictureBox) and then I had a KeyDown event for handling the movement. Inside that event, I was able to handle character movement if I pressed arrow keys, and I've even done a timer-based animation of movement to make it seem more smooth.

However, the problem with KeyDown event is that it fires every time I press the key, meaning that if I'm holding down the arrow key so that the character would continue moving in one direction, the event is fired repeatedly, meaning that the character runs over the screen like a torpedo, because the event is fired as fast as computer can handle it.

开发者_StackOverflow

That's why I decided to use the KeyPress event, so that when I held the key down, the character would move in the designated direction at a steady velocity. However, KeyPress event can't handle arrow keys, which is why I had to override the ProcessDialogKey method in the main form. But if I override it in main form, then the event will be fired every time I press the arrow key, even when I'm not in the game, but for example in main menu or anywhere else. Beside, I think that would be bad practice, if I tried to program things through crossing classes so much anyway.

So, is there any other way for me to handle the KeyPress event on arrows inside my MainCharacter class without affecting other classes? Or is there a chance for me to stay with the KeyDown event, which I already had working, and make it so that it cannot fire repeatedly if I hold down the key? Remember, what I want to achieve is for my character to move fluently when I hold down my key. So far, it works fine, if I press it only once, but usually people hold down keys when they walk in one direction.


Create a direction variable on your MainCharacter class.

OnKeyDown of the left key, set direction to -1, and OnKeyDown of the right key, set direction to 1.

Then OnKeyUp of both left and right keys, set direction to 0.

Then you can move your character based on what value the direction is set to, rather than moving him every time there is a physical key press.

Very pseudo-code: // This example is only concerned about left/right movement.

void Update(){
    // Update position due to current key state.
    this.position.X += this.direction * this.speed;
}

void OnKeyDown(KeyEventArgs e) {
    if(e.Key == Key.Left) {
        player.direction = -1;
    }
    else if(e.Key == Key.Right) {
        player.direction = 1;
    }
}

void OnKeyUp(KeyEventArgs e) {
    if(e.Key == Key.Left || e.Key == Key.Right) {
        player.direction = 0;
    }
}


this.position.X += (this.direction * (this.speed+10));

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜