From 5f8694fea298f2be2f5fa2089b1d06affb02fdc1 Mon Sep 17 00:00:00 2001 From: Derek Christ Date: Sat, 24 May 2025 21:43:20 +0200 Subject: [PATCH] Implement sprite movement --- main.cpp | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/main.cpp b/main.cpp index c54724e..efe886e 100644 --- a/main.cpp +++ b/main.cpp @@ -23,6 +23,8 @@ struct Position { int main() { spdlog::info("Initialize SDL..."); + SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1"); + if (!SDL_Init(SDL_INIT_VIDEO)) { spdlog::critical("Failed to initialize SDL!\nCause: {}", SDL_GetError()); std::terminate(); @@ -53,10 +55,13 @@ int main() { .texture_atlas_index = 0, .custom_size = Vec2{.x = WINDOW_WIDTH, .y = WINDOW_HEIGHT}}); + struct Fruit {}; + world.entity("Sprite1") .set(Position{.x = 0, .y = 0}) .set( - Sprite{.texture = &texture_assets->fruits, .texture_atlas_index = 0}); + Sprite{.texture = &texture_assets->fruits, .texture_atlas_index = 0}) + .add(); world.entity("Sprite2") .set(Position{.x = 32, .y = 32}) @@ -66,8 +71,8 @@ int main() { world.system("RenderSprites") .term_at(0) .singleton() - .each([](flecs::entity e, SdlHandles const &sdl_handles, - Position const &pos, Sprite const &sprite) { + .each([](SdlHandles const &sdl_handles, Position const &pos, + Sprite const &sprite) { TextureAtlasLayout layout = sprite.texture->texture_atlas_layout; uint8_t row = sprite.texture_atlas_index / layout.columns; uint8_t column = sprite.texture_atlas_index % layout.columns; @@ -87,6 +92,25 @@ int main() { &srcrect, &dstrect); }); + world.system("MoveSprites") + .term_at(0) + .singleton() + .each([](ButtonInput const &input, Position &pos, Sprite const &sprite, + Fruit) { + if (input.pressed.contains(SDLK_LEFT)) { + pos.x -= 1; + } + if (input.pressed.contains(SDLK_RIGHT)) { + pos.x += 1; + } + if (input.pressed.contains(SDLK_UP)) { + pos.y -= 1; + } + if (input.pressed.contains(SDLK_DOWN)) { + pos.y += 1; + } + }); + bool exit_gameloop = false; while (!exit_gameloop) { auto *input = world.get_mut(); @@ -119,11 +143,6 @@ int main() { } // Game Logic - if (input->just_pressed.contains(SDLK_X)) - spdlog::info("X pressed!"); - - if (input->just_released.contains(SDLK_X)) - spdlog::info("X released!"); // Render SDL_RenderClear(renderer);