I am working in a simple bouncing ball game. The ball moves right to left at a constant speed and back when it collides with the border of the display. But it jumps every time the the user clicks and then it falls. I apply no friction or something of that kind so when the ball bounces it has to have the exact opposite speed it had when it collided, but due to acceleration, when the frame rate is low it accelerates more than it should and bounces at a greater speed (and higher position), and when the frame rate is too high it bounces at a lower speed (and lower position). This obviously doesn't affect horizontal movement because there is no acceleration in there.
double current_time = SDL_GetTicks();
//for my convenience this is global variable
deltaTime = current_time - *previous_time;
*previous_time = current_time;
//Apply motion in x and y
ball.x += ball.x_speed * deltaTime / 1000;
ball.y += ball.y_speed * deltaTime / 1000;
//Accelerate
//Not quite sure where this should go for physical correctness
ball.y_speed += 1.5 * deltaTime;
ball.rect.x = (int) ball.x;
ball.rect.y = (int) ball.y;
So I now want to know how to make the speed be constant even if the frame rate isn't when I collide with the ground (obviously without getting rid of gravity acceleration).
Update
I didn't find any other relevant code to show you but I will provide a broader look at how I process and display the objects in the game.
I am using SDL to create this game. So I create this struct as a game object:
typedef struct PHYS_Object
{
SDL_Rect collider;
int x_speed, y_speed;
//These two are the exact position of the object
double x, y;
int usesGravity;
SDL_Texture* sprite;
}PHYS_Object;
Then in the main function before entering the main loop I create the objects and provide all the needed information like the image it's gonna use, the position etc... and store the objects that move in an array and objects that collide in other array (some of them are in both).
then in the main loop it goes like this:
//Abbreviated code
while(!quit)
{
if(is_clicked(&button_1))
{
react_to_click();
}else if(is_clicked(&button_2))
{
react_to_click();
}else if(is_clicked(&play_button))
{
ball.y_speed = -250;
}
//Now move all the objects in the array
//according to their speeds and position
//See the code above
PHYS_ApplyMotion(moving_objects_array);
//Now detect and react appropriately to the
//collisions produced after motion occurred
PHYS_DetectCollisions(colliding_objects_array);
SDL_RenderClear(renderer);
SDL_RenderCopy(everything);
SDL_RenderPresent(renderer);
}