🎉 Celebrating 25 Years of GameDev.net! 🎉

Not many can claim 25 years on the Internet! Join us in celebrating this milestone. Learn more about our history, and thank you for being a part of our community!

question that has been asked 20 times :D

Started by
4 comments, last by da_cobra 22 years, 7 months ago
I''m making a tetris game and when I press a key my block moves too fast I already know that I have to use a flag to remember if the key has been pressed or not but for some reason this doesn''t work maybe it''s a small mistake of me but for the moment I can''t find it heres my code ///////////////////////// bool KeyUp ; bool KeyDown ; bool KeyLeft ; bool KeyRight ; gamemain() { .... keyboardinput() ; .... } void WINAPI KeyboardInput() { #define KEYDOWN(name, key) (name[key] & 0x80) char buffer[256]; .... if (KEYDOWN(buffer, DIK_UP) && KeyUp==false) { // Turn the block rotation+=1 ; if (rotation>3) rotation=0 ; KeyUp = true ; } else KeyUp = false ; if (KEYDOWN(buffer, DIK_DOWN) && KeyDown==false) { // Drop the block Start_Y+=16 ; KeyDown = true ; } else KeyDown = false ; ..... } My logic is right but still my blocks move to fast thanx in advance for any help
Advertisement
Try this:


  #define FRAMES_PER_KEY_PRESS 5....int KeyUp = 0;....if (KEYDOWN(buffer, DIK_UP) && KeyUp == 0) {// Turn the blockrotation+=1;if (rotation>3) rotation=0 ;KeyUp = FRAMES_PER_KEY_PRESS;}else if (KeyUp > 0)KeyUp--;  


This way the game will wait FRAMES_PER_KEY_PRESS before considering a new key press.
I don''t understand your function
what to do if I have 5 keys that can be pressed?
also for every key an int then?
Well, your game loop is something like this:


while (1)
{
keyboardinput ();
movestuff ();
drawframe ();
}


The idea of my function is that when the upkey is pressed, the keyUp counter becomes 5. At every call to keyboardinput, keyUp is decreased until it becomes 0, and only then the game processes a new key press. This will make sure that the game can only take one key press every 5 (or whatever number you choose) other frames.

Of course, you should do the same for all the other keys.
The reason why your function doesn't work is that the next frame after you press a key, KeyUp is true, so the else branch is executed and KeyUp becomes false again. So you have rotation+=1 executed every other frame.

A fix for your function is this:

    if (KEYDOWN(buffer, DIK_UP) && KeyUp==false) {// Turn the blockrotation+=1 ;if (rotation>3) rotation=0 ;KeyUp = true ;}if (!KEYDOWN(buffer, DIK_UP))KeyUp = false ;    


This way, after you press a key, KeyUp stays true until you release the key.



Edited by - Diodor on November 17, 2001 2:42:14 PM
thanx diodor, it worked !


Edited by - da_cobra on November 18, 2001 9:15:41 AM

This topic is closed to new replies.

Advertisement