I have two programs right now. One moves an image from left to right and the other moves a rectangle the same. For the image, the movement is jerky and it shudders as it moves. With the rectangle, the movement is also jerky, and the left and right sides distort. Also, sometimes the rectangle turns to a dark gray for the last 100 out of 1000 loops (initially blue rectangle on black background).
In order to fix this, I have tried several solutions. I tried sleeping X time after each loop, I tried creating a frame rate and sleeping until the time difference matched or exceeded the frame time, I tried using a variable based on the time difference and desired fps to update the movement, and I have tried counter loops. None of them work and produce a similar effect.
So my question is, how can I create a proper timing loop and/or movement formula for my image and shape movement in order to create smooth movements? I don’t want people to get motion sick playing my games
I am running SDL2/C++ on Ubuntu 16.04. Here is some code for one of my rectangle attempts:
#include </usr/include/SDL2/SDL.h>
#include
void init(SDL_Window * &win, SDL_Renderer * &ren,
int w, int h){
SDL_Init(SDL_INIT_EVERYTHING);
win = SDL_CreateWindow(“Template”,
100, 100, w, h, SDL_WINDOW_SHOWN);
ren = SDL_CreateRenderer(win, -1,
SDL_RENDERER_ACCELERATED |
SDL_RENDERER_PRESENTVSYNC);
}
SDL_Rect makeRect(int x, int y, int w, int h){
SDL_Rect rect;
rect.x = x;
rect.y = y;
rect.w = w;
rect.h = h;
return rect;
}
void clearScreen(SDL_Renderer * &ren){
SDL_SetRenderDrawColor(ren, 0, 0, 0, 255);
SDL_RenderClear(ren);
}
int main(int argc, char* argv[]){
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
float speed = 0.2;
float t0;
float position_X = 50.0;
float fps = 60;
float fpms = fps / 1000.0;
SDL_Window *window;
SDL_Renderer *renderer;
init(window, renderer, SCREEN_WIDTH, SCREEN_HEIGHT);
SDL_Rect r = makeRect(50, 50, 50, 50);
t0 = SDL_GetTicks();
for (int i = 0; i < 1000; i++){
clearScreen(renderer);
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
SDL_RenderFillRect(renderer, &r);
SDL_RenderPresent(renderer);
position_X += speed;
while ((SDL_GetTicks() - t0) < fpms);
t0 = SDL_GetTicks();
r.x = (int)position_X;
std::cout << "Position: " << (int)position_X << std::endl;
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}