我在屏幕上有一个正方形,如果按住某个特定键,我希望它每25ms向右移动5个像素。我不明白为什么它可以正常使用某些键(例如向上),但不能像其他键那样工作(例如a)。如果不能正常工作,我的意思是,不是花费6秒钟来穿过整个屏幕,而是在我停止按下按键后,需要一段时间才能停止移动。
这是完整的代码:
#include <stdio.h>
#include <stdlib.h>
#include <SDL2/SDL.h>
#include <stdbool.h>
#define LARGEUR 1200
#define HAUTEUR 800
#define DELAI_RAFRAICHISSEMENT 25
int main(int argc, char *argv[])
{
int tempsActuel = 0, tempsPrecedent = 0;
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK) != 0 )
{
fprintf(stdout,"Echec de l'initialisation de la SDL (%s)\n",SDL_GetError());
return -1;
}
SDL_Window* window;
window = SDL_CreateWindow("1 2 3 Piano",SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, LARGEUR, HAUTEUR, SDL_WINDOW_SHOWN);
SDL_Renderer* renderer;
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_Event event;
SDL_Rect ecran = {0, 0, LARGEUR, HAUTEUR};
SDL_Rect carre = {0, 775, 25, 25};
SDL_Rect carreDroite = {0, 775, 0, 25};
SDL_Rect carreGauche = {0, 775, 0, 25};
bool continuer = true;
while(continuer){
tempsActuel = SDL_GetTicks();
if (tempsActuel - tempsPrecedent < DELAI_RAFRAICHISSEMENT){
SDL_Delay(DELAI_RAFRAICHISSEMENT - (tempsActuel - tempsPrecedent));
}
tempsPrecedent = SDL_GetTicks();
SDL_SetRenderDrawColor(renderer, 255,255,255,0);
SDL_RenderFillRect(renderer, &ecran);
SDL_SetRenderDrawColor(renderer, 0,0,0,0);
if(carre.x <= 1175)
SDL_RenderFillRect(renderer, &carre);
else{
carreDroite.x = carre.x;
carreDroite.w = LARGEUR - carre.x;
carreGauche.w = 25 - carreDroite.w;
SDL_RenderFillRect(renderer, &carreDroite);
SDL_RenderFillRect(renderer, &carreGauche);
}
SDL_RenderPresent(renderer);
SDL_PollEvent(&event);
switch(event.type){
case SDL_KEYDOWN:
if(event.key.keysym.sym == SDLK_a)
carre.x = (carre.x+5) % LARGEUR;
else if(event.key.keysym.sym == SDLK_ESCAPE)
continuer = false;
break;
case SDL_QUIT:
continuer = false;
}
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
就像我说的,如果我用SDLK_UP替换SDLK_a,它可以正常工作。按预期工作的键非常少。