当我运行我的应用程序时,我得到了大量的输入滞后。
更多详细信息:当我按“ w”,“ a”,“ s”,“ d”(分配给我的输入键)时,对象会移动,但是在释放键后,对象会继续移动很长时间。源代码在下面,但是代码的一小部分已被删节,以缩短问题,但是,如果下面的源代码无法编译,我将所有代码都放在github上。https://github.com/TreeStain/DodgeLinuxGame.git谢谢您的宝贵时间。-特里斯坦
dodge.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;
}
render.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();
}
object.h:
typedef struct
{
int x, y, w, h, ySpeed, xSpeed;
char sprite;
}object;
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);
}
从循环的顶部开始:while( (in = getch()) == ERR) {}
将快速调用getch(),直到检测到按键。如果未检测到按键,getch()将返回ERR。什么while(getch() != ERR) {}
是不断调用getch()直到从队列中删除所有缓冲的输入字符,然后getch()返回ERR并继续前进。然后该循环应睡眠〜17ms并重复执行。这些行应强制循环每隔约17毫秒仅“计数”一次按键,并且不超过此次数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句