Home > Mobile >  C and SDL how to move a point in the screen
C and SDL how to move a point in the screen

Time:12-13

I am using SDL alongside the c I want to build a simple game where the little dot moves in the screen I tried to use a for loop but i did not help since the trail exists so how can i move a point in the screen here is my code:

#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <time.h>
#include <malloc.h>
#include <math.h>
#include "SDL/include/SDL.h"
#include "SDL/include/SDL_render.h"

#define WIDTH 800.0f
#define HEIGHT 600.0f

int main()
{
  bool quit = false;

  SDL_Event event;

  // init SDL
  SDL_Init(SDL_INIT_VIDEO);
  SDL_Window * window = SDL_CreateWindow("SDL2 line drawing",
      SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, 0);

  SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);

  // handle events
  while (!quit)
  {
      SDL_Delay(10);
      SDL_PollEvent(&event);

      switch (event.type)
      {
          case SDL_QUIT:
              quit = true;
              break;
      }

      SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
      SDL_RenderClear(renderer);

      SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);

      SDL_RenderDrawLine(renderer, 100, 100, 500, 500);

      /*for (int i = 0; i < 100; i  ) {*/
        /*SDL_RenderDrawPoint(renderer, 150   i, 150);*/
        /*sleep(1);*/
        /*SDL_RenderPresent(renderer);*/
      /*}*/

      // render window
      SDL_RenderPresent(renderer);
  }

  // cleanup 
  SDL_DestroyRenderer(renderer);
  SDL_DestroyWindow(window);
  SDL_Quit();

  return 0;
}


what I want to happen is a point that changes its position on the screen how can it be done to remove the point and repaint it somewhere else on the screen?

CodePudding user response:

Render your dot ONCE for each while (!quit), not all the 100 times for the whole movement you want to animate. The way your commented code does it you get all the 100 positions in each loop, i.e. for each SDL_RenderClear(renderer);.

  • Related