How do I detect key presses

Started by
14 comments, last by GameDev.net 18 years, 4 months ago
How can I tell it to only move every second? I dont really know how to use time in a C++ program.
Advertisement
time is a lot more complicated :/ you'll want to write a timer class for your project that is consistently accurate.
If you have a dos project you can get the cpu ticks since program start pretty easy. This value is updated 18.2 times per seconds (can be programmed to use a higher freq.)
Correct me if Im wrong.

long start_time, current_time;game_loop(){  start_time = *(long far*)0x0000046CL;  ...do work here...  do {    current_time = *(long far*)0x0000046CL;  } while(current_time < start_time + 18); // wait ~1 sec.}
Get a nice library, i recommend allegro, i think it's probably the most underrated game library out there,especially for beginners. It has nice examples & very good documentation.

Good luck
Had a quick scan through this discussion, so sorry if I've repeated someones advice.

If it's windows you're using, an easy way is to use kbhit();

...  while( true )  {    if ( kbhit() == true )    {      /* Code goes here */    }  }...


To retrieve what key or character was pressed; you can use getch().

This doesn't work in Linux as far as I know.

Daed.


If you are stuck using getch() to get the special keys like UP, DOWN, PAGEUP, PAGEDOWN, etc. you need to make one more call to getch() but only on certain conditions..


int key1, key2;
if (kbhit()){
key1 = getch();
if (key1 == 0){ // A special key was hit.
// now we get the key that was pressed
key2 = getch();
cout <

This topic is closed to new replies.

Advertisement