[DirectX10] Key input help?!

Started by
0 comments, last by Tsus 12 years, 4 months ago
Hi , Im trying to make my program detect a 'Keypress' not a keydown. I have it working although beacuse its detecting keydown and not keypress it repeats what i want it to do extremly fast.
In Xna i had this problem but fixed it simply by adding a second keyboard variabe for the previous key press abit like this
pseudo:
if (keypress = up && !prevkeypress = up)
{
sprite.x +=1;
}

prevkeypress = keypress;

SHORT WINAPI GetAsyncKeyState // keyinput
(
__in int vKey

);



if (GetAsyncKeyState(VK_DOWN))
{
//statenumber += 1;
}



This detects keydown , but i just want keypress?


Advertisement
Hi!

Well, you kind of mentioned the solution. :) We need to memorize the last state.
Let's see whether we can make some little helper for that.
First, some function that checks for keydown. (Jep, thats not what you want, but we will build up on that.)

// Checks whether a key is down.
bool IsKeyDown(char key)
{
return GetAsyncKeyState(key) < 0;
}

Now comes the interesting part: the key press method.
We need to memorize the last state, right? We could either build a class for that and keep it somewhere static (too much stuff to build around that..) or we could use global variables (uh, global scope..).
Instead, let's write a global function that declares static variables in it. The beauty of it is we get a variable with global lifetime (like we would get with a global variable) but only with local scope (not like a global variable!).
// Checks whether a key is pressed.
bool IsKeyPressed(char key)
{
static bool keys[256]; // One flag for each key... local scope but global lifetime!
bool currState = IsKeyDown(key); // get current state.
if (currState && !keys[key]) // compare to last state -> is pressed?
{
keys[key] = currState; // memorize state for next time
return true; // report: yes!
}
keys[key] = currState; // memorize state for next time
return false; // report: no!
}


Well, and just a quick test to see whether it works...
int _tmain(int argc, _TCHAR* argv[])
{
while (!IsKeyDown('E'))
{
if (IsKeyPressed(VK_DOWN))
printf("Pressed!");

Sleep(10);
}
return 0;
}


Looks fine on my side. :)

Cheers!

This topic is closed to new replies.

Advertisement