You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.1 KiB
C++

#include "components/point.hpp"
#include "components/player.hpp"
#include "components/texture.hpp"
#include "components/velocity.hpp"
#include "window.hpp"
3 months ago
#include <chrono>
#include <thread>
#include <entt/entt.hpp>
#include <SDL2/SDL.h>
constexpr std::chrono::microseconds FRAME_TIME (1'000'000 / 60);
3 months ago
static bool handleInputs(entt::registry& registry);
3 months ago
int main()
{
if (auto err = sdl2Initialize(); err)
return err;
entt::registry registry;
const auto ent = registry.create();
registry.emplace<Player>(ent);
registry.emplace<Point>(ent, 0.f, WINDOW_HEIGHT - 100.f);
registry.emplace<Velocity>(ent, 0.f, 0.f);
registry.emplace<Texture>(ent, "img/player.png");
do {
const auto now = std::chrono::high_resolution_clock::now();
3 months ago
SDL_RenderClear(renderer);
registry.view<Texture, Point>().each([](auto& tex, auto& p) { tex(renderer, p); });
3 months ago
SDL_RenderPresent(renderer);
registry.view<Velocity, Point>().each([](auto& v, auto& p) { p += v; });
3 months ago
std::this_thread::sleep_until(now + FRAME_TIME);
} while (handleInputs(registry));
3 months ago
}
bool handleInputs(entt::registry& registry)
3 months ago
{
bool quit = false;
3 months ago
for (SDL_Event e; SDL_PollEvent(&e);) {
if (e.type == SDL_QUIT) {
quit = true;
} else if (e.type == SDL_KEYDOWN && !e.key.repeat) {
auto view = registry.view<Player, Velocity>();
switch (e.key.keysym.sym) {
case SDLK_d:
view.each([](Player& p, Velocity& v) { v.x += 1.5f; });
break;
case SDLK_a:
view.each([](Player& p, Velocity& v) { v.x -= 1.5f; });
break;
}
} else if (e.type == SDL_KEYUP && !e.key.repeat) {
auto view = registry.view<Player, Velocity>();
switch (e.key.keysym.sym) {
case SDLK_d:
view.each([](Player& p, Velocity& v) { v.x -= 1.5f; });
break;
case SDLK_a:
view.each([](Player& p, Velocity& v) { v.x += 1.5f; });
break;
}
3 months ago
}
}
return !quit;
3 months ago
}