#include #include #include #include #define WIDTH 800 #define HEIGHT 600 typedef struct { int x; int y; } vec2d; typedef struct { vec2d pos; vec2d speed; vec2d acc; int size; } ball; vec2d add_vec2d(vec2d a, vec2d b){ vec2d c = { .x = 0, .y = 0 }; c.x = a.x + b.x; c.y = a.y + b.y; return c; } void bounce_ball(ball *b, int x, int y) { if (b->pos.x >= x || b->pos.x < 0) b->speed.x *= -1; if (b->pos.y >= y || b->pos.y < 0) b->speed.y *= -1; } void update_ball(ball *b) { b->pos = add_vec2d(b->pos, b->speed); b->speed = add_vec2d(b->speed, b->acc); bounce_ball(b, WIDTH, HEIGHT); } void update(SDL_Renderer *ren, unsigned int ticks, ball *b){ SDL_SetRenderDrawColor(ren, 128, 128, 128, 255); SDL_RenderClear(ren); SDL_SetRenderDrawColor(ren, 255, 0, 0, 255); SDL_Rect ballrect = { .x = b->pos.x, .y = b->pos.y, .w = b->size / 2, .h = b->size / 2 }; SDL_RenderFillRect(ren, &ballrect); update_ball(b); } int main(int argc, char** argv) { if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "Error initializing SDL"); return 1; } ball b; b.pos.x = 100; b.pos.y = 100; b.speed.x = 5; b.speed.y = 1; b.acc.x = 0; b.acc.y = 0; b.size = 30; SDL_Window *win = SDL_CreateWindow("New Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL); SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); bool running = true; SDL_Event ev; unsigned int ticks = 0; while (running) { while (SDL_PollEvent(&ev)){ ticks = SDL_GetTicks(); if (ev.type == SDL_QUIT){ running = false; break; } unsigned int newticks = SDL_GetTicks(); ticks = (newticks - ticks) / 1000; } update(ren, ticks, &b); SDL_RenderPresent(ren); } SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); return (0); }