Detecting Keypresses

Started by
3 comments, last by Rob Loach 18 years, 8 months ago
Hi guys, On my game I'm doing, when the user presses a key to turn the object, it works, but I need to know if there is a C++/C/Allegro function I can use to make the game think the key is no longer pressed, if you know what I mean. Do you guys know of any such function, or can you help me figure out a way to overcome this obstacle? Thanks!
Advertisement
you might want to look into buffered input. Are you using getasynckeystate or dircet input?

buffered input basically chcks if key is down, then executes an action but wont recognize keypress again till the key is released then pressed, or you could just check for keyup instead. WHich is the more hacked way of doing it.
We have youth, how about a fountain of smart.e4 e5 f4 d5
I haven't heard of any function, perhaps there is one but I don't know of it.

What you could do is have an input handler within your game loop set to detect when a key is pressed, and when it is released. You could use a switch or if statement to determine what to do on certain keypresses. You could then set boolean variables to true or false depending on whether said key is pressed or not.

Pseudocode:

bool spacepressed; // Boolean variable - true means space is pressed, false means it isn't.

Button press detected:

if(Button pressed is space)
{
spacepressed=true;
}


Button release detected:

if(Button released is space)
{
spacepressed=false;
}


while(spacepressed)
{
do what you want while space is held down - if you have a game loop set up one press will only affect its own tick, providing your keyhandler function is in the game loop as well
}


I hope this has given you a handle on how to do it. This is how I do it with SDL, if you're confused please let me know and I'll try and explain further.

HTH,

ukdeveloper.
I get it! Thank you guys a bunch!
It might actually be better to have an array control it:
bool bKeyDown = bool array of all keys on the keyboard;Event_KeyDown(keyNumber){    bKeyDown[keyNumber] = true;}Event_KeyUp(keyNumber){    bKeyDown[keyNumber] = false;}

You could then make an enumeration of all the keys to determine which key was pressed:
enum Key {    A=32,    B=61,    C=41 // ... and so on}if(bKeyDown[Key.B])    // The B key is down!!!
This might even already be done by the API you're using, just check the documentation. Oh, and excuse my horrible pseudocode.
Rob Loach [Website] [Projects] [Contact]

This topic is closed to new replies.

Advertisement