I'm new to SDL programming and I'm not quite sure I got how it handles events. Given an instance like this defined in "game.c":
static struct {
SDL_Window* window;
SDL_Renderer* renderer;
BinaryTree* objects;
} game = { NULL, NULL, NULL };
(Which of course gets properly initialized)
My game loop is defined in the same file as follows:
void game_run() {
bool closeRequested = false;
while(closeRequested == false) {
SDL_RenderClear(game.renderer);
binaryTree_startIteration(game.objects);
while(binaryTree_hasNext(game.objects)) {
GameObject* gameObject = (GameObject*) binaryTree_getNext(game.objects);
SDL_Event event;
while(SDL_PollEvent(&event)) {
if(event.type == SDL_QUIT) {
closeRequested = true;
}
else {
if(event.type == SDL_KEYDOWN) {
gameObject_onKeyPressed(gameObject);
if(event.key.keysym.scancode == SDL_SCANCODE_UP) {
gameObject_onUpKeyPressed(gameObject);
}
if(event.key.keysym.scancode == SDL_SCANCODE_DOWN) {
gameObject_onDownKeyPressed(gameObject);
}
if(event.key.keysym.scancode == SDL_SCANCODE_LEFT) {
gameObject_onLeftKeyPressed(gameObject);
}
if(event.key.keysym.scancode == SDL_SCANCODE_RIGHT) {
gameObject_onRightKeyPressed(gameObject);
}
}
if(event.type == SDL_KEYUP) {
//
}
}
}
gameObject_onRendering(gameObject);
SDL_RenderCopy(renderer, gameObject_getTexture(gameObject), NULL, gameObject_getDestination(gameObject));
}
SDL_RenderPresent(game.renderer);
}
}
game.objects contains every object which has to be rendered (via game.renderer) onto the the window (game.window). So, on each frame game.objects gets iterated on and for each element various functions get executed, before its texture is loaded to the renderer.
Of course gameObject_onRightKeyPressed() is called only if the right key was pressed, so if this function is defined as
void gameObject_onRightKeyPressed(GameObject* gameObject) {
gameObject->destination.x += 1,
}
On each frame that the right key is pressed, gameObject's texture will move by 1 pixel to the right.
This works perfectly if game.objects contains only one element, but if a second element gets added, only the first one will smoothly respond to my input, while the other will move by 1 or 2 pixels just once in a while by keeping the right key pressed. It's like the first element contained in game.objects "steals" the input, so that when the second element's turn comes, there's no input for it to respond to. What did I do wrong?