Tri*_*hur 6 c loops input ncurses delay
当我运行我的应用程序时,我遇到了大量的输入延迟。
更多细节:当我按下“w”、“a”、“s”、“d”(我指定的输入键)时,对象会移动,但是在释放键后它会继续移动很长时间。源代码在下面,但是代码的一小部分已经被剪掉以缩短问题,但是如果下面的源代码不能编译,我将所有代码放在 github 上。 https://github.com/TreeStain/DodgeLinuxGame.git谢谢你的时间。-特里斯坦
道奇.c:
#define ASPECT_RATIO_X 2
#define ASPECT_RATIO_Y 1
#define FRAMES_PER_SECOND 60
#include <ncurses.h>
#include "object.h"
#include "render.h"
int main()
{
initscr();
cbreak();
noecho();
nodelay(stdscr, 1);
object objs[1];
object colObj; colObj.x = 10; colObj.y = 6;
colObj.w = 2; colObj.h = 2;
colObj.sprite = '*';
colObj.ySpeed = 1;
colObj.xSpeed = 1;
objs[0] = colObj;
//halfdelay(1);
while (1)
{
char in = getch();
if (in == 'w')
objs[0].y -= objs[0].ySpeed * ASPECT_RATIO_Y;
if (in == 's')
objs[0].y += objs[0].ySpeed * ASPECT_RATIO_Y;
if (in == 'a')
objs[0].x -= objs[0].xSpeed * ASPECT_RATIO_X;
if (in == 'd')
objs[0].x += objs[0].xSpeed * ASPECT_RATIO_X;
render(objs, 1);
napms(FRAMES_PER_SECOND);
}
getch();
endwin();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
渲染.h:
void render(object obj[], int objectNum);
void render(object obj[], int objectNum) //Takes array of objects and prints them to screen
{
int x, y, i, scrWidth, scrHeight;
getmaxyx(stdscr, scrHeight, scrWidth); //Get terminal height and width
for (y = 0; y < scrHeight; y++)
{
for (x = 0; x < scrWidth; x++)
{
mvprintw(y, x, " ");
}
}
for (i = 0; i < objectNum; i++)
{
int xprint = 0, yprint = 0;
for (yprint = obj[i].y; yprint < obj[i].y + (obj[i].h * ASPECT_RATIO_Y); yprint++)
{
for (xprint = obj[i].x; xprint < obj[i].x + (obj[i].w * ASPECT_RATIO_X); xprint++)
mvprintw(yprint, xprint, "%c", obj[i].sprite);
}
}
refresh();
}
Run Code Online (Sandbox Code Playgroud)
对象.h:
typedef struct
{
int x, y, w, h, ySpeed, xSpeed;
char sprite;
}object;
Run Code Online (Sandbox Code Playgroud)
PS 请随时批评我的方法和代码,因为我在编程方面还很陌生,可以接受我能得到的所有批评。
我相信原因是因为 getch() 一次只会释放一个输入字符(即使输入流中排队有很多字符),因此如果它们排队的速度比您从流中“删除”它们的速度快,则循环即使在您释放按键后,也会继续执行,直到队列清空。此外,您还需要 (1000 / FRAMES_PER_SECOND) 来获得所需的延迟时间(以毫秒为单位)(这会产生每秒 60 帧)。
请在 while 循环中尝试此操作。
while (1)
{
char in;
/* We are ready for a new frame. Keep calling getch() until we hear a keypress */
while( (in = getch()) == ERR) {}
if (in == 'w')
objs[0].y -= objs[0].ySpeed * ASPECT_RATIO_Y;
if (in == 's')
objs[0].y += objs[0].ySpeed * ASPECT_RATIO_Y;
if (in == 'a')
objs[0].x -= objs[0].xSpeed * ASPECT_RATIO_X;
if (in == 'd')
objs[0].x += objs[0].xSpeed * ASPECT_RATIO_X;
render(objs, 1);
/* Clear out any other characters that have been buffered */
while(getch() != ERR) {}
napms(1000 / FRAMES_PER_SECOND);
}
Run Code Online (Sandbox Code Playgroud)
从循环顶部开始:while( (in = getch()) == ERR) {}将快速调用 getch() 直到检测到按键。如果未检测到按键,getch() 将返回 ERR。所做while(getch() != ERR) {}的就是不断调用 getch() 直到所有缓冲的输入字符都从队列中删除,然后 getch() 返回 ERR 并继续。然后循环应该休眠约 17 毫秒并重复。这些行应该强制循环每约 17 毫秒仅“计数”一次按键,并且不会超过此频率。
请参阅: http: //linux.die.net/man/3/getch