I've just started getting into game development, SDL in particular, so please go easy on me. I'm struggling to understand why my player's position isn't chaning when I press the left arrow button.
main.cpp
#include <iostream>
#include "SDL2/SDL.h"
#include "SDL2/SDL_image.h"
typedef struct
{
float x, y;
SDL_Texture *sprite;
} Player;
int processEvents(SDL_Window *window, Player *player) {
SDL_Event event;
int done = 0;
while(SDL_PollEvent(&event)) {
switch(event.type) {
case SDL_WINDOWEVENT_CLOSE: {
if(window) {
SDL_DestroyWindow(window);
window = NULL;
done = 1;
}
}
break;
case SDL_QUIT: {
done = 1;
}
break;
}
}
const Uint8 *keyState = SDL_GetKeyboardState(NULL);
if( keyState[SDL_SCANCODE_LEFT] ) {
player->x = 120;
}
return done;
}
void render(SDL_Renderer *renderer, Player *player) {
SDL_RenderClear(renderer);
SDL_Rect playerRect;
playerRect.x = 0;
playerRect.y = 0;
playerRect.w = 32;
playerRect.h = 32;
SDL_RenderCopy(renderer, player->sprite, NULL, &playerRect);
SDL_RenderPresent(renderer);
}
void update(Player *player) {
player->x += 10;
}
int main( int argc, char *args[] ) {
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Event event;
Player player;
player.x = 50;
player.y = 0;
SDL_Init(SDL_INIT_EVERYTHING);
window = SDL_CreateWindow("Dungeon", 100 , 100, 640, 480, SDL_WINDOW_SHOWN);
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
player.sprite = IMG_LoadTexture(renderer, "assets/player.png");
int done = 0;
while( !done ) {
done = processEvents(window, &player);
update(&player);
render(renderer, &player);
}
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit;
return 0;
}
Any help would be much appreciated.
Thanks :)
processEvents
sets the player's x-position to the same value each frame, instead of incrementing it like update does. EitherprocessEvents
orupdate
should handle player movement. Lastly, thedstRect
(playerRect
) forSDL_RenderCopy
needs to useplayer->x
andplayer->y
to position on the window. ThedstRect
width and height you have are fine, but be aware that if thesrcRect
(player.sprite
) width and height differ from that of thedstRect
thenSDL_RenderCopy
will scale theplayer.sprite
. \$\endgroup\$