Key repeat delay in SDL
I am trying to get the keyboard delay effect in a menu while the keyboard is held down. Currently it works, but not after changing directions. For example I could press and hold right and the cursor world move over right, then pause, then continually travel right (as expected). I could release and press right or press and hold right and it would work. Pressing and holding left doesn't work, the cursor goes at full speed immediately. Strangely though if i release and hold left after that it works. Pressing and holding right after that causes the cursor to move at full speed immediately, and like above this only affects the first time.
Here is the function that I am working on: (many of the variables are global, o if one is not declared in the function it is global)
int handleEvents() {
static int lcount = 0;
static int rcount = 0;
while(SDL_PollEvent(&e)) {
if(e.type == SDL_QUIT) end++; //quit code
if(e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym) {
case SDLK_ESCAPE: end++; break;
case SDLK_LEFT: lDown = 1; break;
case SDLK_RIGHT: rDown = 1; break;
}
}
if(e.type == SDL_KEYUP) {
switch (e.key.keysym.sym) {
case SDLK_LEFT: lDown = 0; break;
case SDLK_RIGHT: rDown = 0; break;
}
}
}
int now = SDL_GetTicks();
if (lDown && curLocation > 0 && (now-ltime > 1500 || (now-ltime > 250 && lcount>0))) {
curLocation--;
lcount++;
ltime = SDL_GetTicks();
}
if (rDown && curLocation < 18 && (now-rtime > 1500 || (now-rtime > 250 && rcount>0))) {
curLocation++;
rcount++;
rtime = SDL_GetTicks();
}
if (!lDown) {
lcount = 0;
ltime = now - 1500;
}
if (!rDown) {
rcount = 0;
rtime = now - 1500;
}
return 0;
}
After reading through earlier questions on this site i found SDL_EnableKeyRepeat()
. I couldn't find any examples of how to use it in a program, but I tried it anyway. Here is a cut down version of the same function:
int handleEvents() {
int mouseMotion = 0;
SDL_EnableKeyRepeat(500, 250);
while(SDL_PollEvent(&e)) {
if(e.type == SDL_QUIT) end++; //quit code
if(e.type == SDL_KEYDOWN) {
switch (e.key.keysym.sym) {
case SDLK_ESCAPE: end++; break;
case SDLK_LEFT: curLocation--; break;
case SDLK_RIGHT: curLocation++; break;
}
}
}
return 0;
}
This one has no repeat at all.
链接地址: http://www.djcxy.com/p/33860.html下一篇: SDL中的密钥重复延迟