bouncing.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include <SDL2/SDL.h>
  5. #define WIDTH 800
  6. #define HEIGHT 600
  7. typedef struct {
  8. int x;
  9. int y;
  10. } vec2d;
  11. typedef struct {
  12. vec2d pos;
  13. vec2d speed;
  14. vec2d acc;
  15. int size;
  16. } ball;
  17. vec2d add_vec2d(vec2d a, vec2d b){
  18. vec2d c = { .x = 0, .y = 0 };
  19. c.x = a.x + b.x;
  20. c.y = a.y + b.y;
  21. return c;
  22. }
  23. void bounce_ball(ball *b, int x, int y) {
  24. if (b->pos.x >= x || b->pos.x < 0)
  25. b->speed.x *= -1;
  26. if (b->pos.y >= y || b->pos.y < 0)
  27. b->speed.y *= -1;
  28. }
  29. void update_ball(ball *b) {
  30. b->pos = add_vec2d(b->pos, b->speed);
  31. b->speed = add_vec2d(b->speed, b->acc);
  32. bounce_ball(b, WIDTH, HEIGHT);
  33. }
  34. void update(SDL_Renderer *ren, unsigned int ticks, ball *b){
  35. SDL_SetRenderDrawColor(ren, 128, 128, 128, 255);
  36. SDL_RenderClear(ren);
  37. SDL_SetRenderDrawColor(ren, 255, 0, 0, 255);
  38. SDL_Rect ballrect = {
  39. .x = b->pos.x,
  40. .y = b->pos.y,
  41. .w = b->size / 2,
  42. .h = b->size / 2
  43. };
  44. SDL_RenderFillRect(ren, &ballrect);
  45. update_ball(b);
  46. }
  47. int main(int argc, char** argv) {
  48. if (SDL_Init(SDL_INIT_VIDEO) != 0) {
  49. fprintf(stderr, "Error initializing SDL");
  50. return 1;
  51. }
  52. ball b;
  53. b.pos.x = 100;
  54. b.pos.y = 100;
  55. b.speed.x = 5;
  56. b.speed.y = 1;
  57. b.acc.x = 0;
  58. b.acc.y = 0;
  59. b.size = 30;
  60. SDL_Window *win = SDL_CreateWindow("New Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_OPENGL);
  61. SDL_Renderer *ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  62. bool running = true;
  63. SDL_Event ev;
  64. unsigned int ticks = 0;
  65. while (running) {
  66. while (SDL_PollEvent(&ev)){
  67. ticks = SDL_GetTicks();
  68. if (ev.type == SDL_QUIT){
  69. running = false;
  70. break;
  71. }
  72. unsigned int newticks = SDL_GetTicks();
  73. ticks = (newticks - ticks) / 1000;
  74. }
  75. update(ren, ticks, &b);
  76. SDL_RenderPresent(ren);
  77. }
  78. SDL_DestroyRenderer(ren);
  79. SDL_DestroyWindow(win);
  80. SDL_Quit();
  81. return (0);
  82. }