I'm writing a small ball game. I have a function called gravity
and I also have a while loop that checks whether the user wants to move the ball using wsad keys.
Do I need to multi thread this or is there another way out? I cut out some of the irrelevant code for setting up the program. Here is just the stuff that matters:
while(1) {
enableGravity();
char ch = getch();// i know getch() is not going to cut it
//maybe 2 different f() multi threaded , for gravity and position,
f(ch == 'w' || ch == 'W')
updateObjPosition('U');
else if(ch == 's' || ch == 'S')
updateObjPosition('D');
else if(ch == 'a' || ch == 'A')
updateObjPosition('L');
else if(ch == 'd' || ch == 'D')
updateObjPosition('R');
}
I have these functions in main. I need the program to enable gravity and also be able to accept input to move the ball through updateObjPosition()
simultaneously .
You could use multiple threads. A more obvious possibility would be a non-blocking keyboard read.
If you're doing this on Windows, you probably have a _kbhit
in your standard library that will tell you if a key on the keyboard has been pressed. If you're using curses, you can use nodelay
to tell getch to return immediately, whether a key has been pressed or not. Other systems may do things in different ways still, but you get the general idea...
You don't need to multi-thread. You just need an API that returns TRUE if a specified key is currently pressed down. That will likely be platform dependent. What platform are you building/running on?
For example on Win32: GetAsyncKeyState
As you have mentioned you are using old Borland compiler on TC 3.1 in the old conio.h there was a function
kbhit();
the function was a one shot solution for getting if any key is pressed on the keyboard so here is your loop to get key input
int getKey(){
if(kbhit){
return getch();
}
return -1;
}
By they way you should upgrade to VC 08 Atleast!
For your simple project where the logic loop i guess will be quite small this will handle all the pain for you but if you write a longer application with hard logic then you will have to use better and Asynchronous methods for IO and those methods basically involve working on 2 threads 1 getting Input and the other doing logic operations ..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.