So che hai già selezionato una risposta .. ma qui c'è un codice reale di come lo faccio normalmente con un array. :)
prima definire questo da qualche parte.
bool KEYS[322]; // 322 is the number of SDLK_DOWN events
for(int i = 0; i < 322; i++) { // init them all to false
KEYS[i] = false;
}
SDL_EnableKeyRepeat(0,0); // you can configure this how you want, but it makes it nice for when you want to register a key continuously being held down
Poi più tardi, creare una funzione di tastiera(), che registrerà l'input da tastiera
void keyboard() {
// message processing loop
SDL_Event event;
while (SDL_PollEvent(&event)) {
// check for messages
switch (event.type) {
// exit if the window is closed
case SDL_QUIT:
game_state = 0; // set game state to done,(do what you want here)
break;
// check for keypresses
case SDL_KEYDOWN:
KEYS[event.key.keysym.sym] = true;
break;
case SDL_KEYUP:
KEYS[event.key.keysym.sym] = false;
break;
default:
break;
}
} // end of message processing
}
Poi, quando in realtà si desidera utilizzare l'input da tastiera cioè una funzione handleInput(), potrebbe essere simile questo:
void handleInput() {
if(KEYS[SDLK_LEFT]) { // move left
if(player->x - player->speed >= 0) {
player->x -= player->speed;
}
}
if(KEYS[SDLK_RIGHT]) { // move right
if(player->x + player->speed <= screen->w) {
player->x += player->speed;
}
}
if(KEYS[SDLK_UP]) { // move up
if(player->y - player->speed >= 0) {
player->y -= player->speed;
}
}
if(KEYS[SDLK_DOWN]) { // move down
if(player->y + player->speed <= screen->h) {
player->y += player->speed;
}
}
if(KEYS[SDLK_s]) { // shoot
if(SDL_GetTicks() - player->lastShot > player->shotDelay) {
shootbeam(player->beam);
}
}
if(KEYS[SDLK_q]) {
if(player->beam == PLAYER_BEAM_CHARGE) {
player->beam = PLAYER_BEAM_NORMAL;
} else {
player->beam = PLAYER_BEAM_CHARGE;
}
}
if(KEYS[SDLK_r]) {
reset();
}
if(KEYS[SDLK_ESCAPE]) {
gamestate = 0;
}
}
E naturalmente si può facilmente fare quello che hai intenzione di fare
while(KEYS[SDLK_s]) {
// do something
keyboard(); // don't forget to redetect which keys are being pressed!
}
** Versione aggiornata sul mio sito web: ** Per il bene di non inviare un sacco di codice sorgente, è possibile visualizzare una classe tastiera SDL completa in C++ che supporta
- singolo ingresso chiave
- simultanea chiave Combos (Keys tutti premuti in qualsiasi ordine)
- sequenziale chiave Combonations (Keys tutti premuti in un ordine specifico)
http://kennycason.com/posts/2009-09-20-sdl-simple-space-shooter-game-demo-part-i.html (se avete problemi, fatemelo sapere)
fonte
2010-09-28 19:01:02
Perché grazie mille, non so come apprezzare il tuo aiuto! – deluvas