Okay, so I am using SDL and rectangular collision detection. Whenever the player collides with the wall/block, he stops on top if it. Gravity is implemented.
I noticed an error though; whenever the player jumps from a high place or falls from very high up, the player actually doesnt collide with the block. The function detects a collision and the player stops, but it is moving so fast that there is a gap of like 5 pixels between it and the platform. When the player is only 32 pixels, this is a big deal.
How can I make it so that whenever the player falls from any distance at any speed that it will actually collide directly with the platform, rather than stopping 5 pixels before it hits.
Thanks in advance for any help.
Here are the code-bits:
bool check_collision( SDL_Rect A, SDL_Rect B )
{
//The sides of the rectangles
int leftA, leftB;
int rightA, rightB;
int topA, topB;
int bottomA, bottomB;
//Calculate the sides of rect A
leftA = A.x;
rightA = A.x + A.w;
topA = A.y;
bottomA = A.y + A.h;
//Calculate the sides of rect B
leftB = B.x;
rightB = B.x + B.w;
topB = B.y;
bottomB = B.y + B.h;
//If any of the sides from A are outside of B
if( bottomA < topB )
{
return false;
}
if( topA > bottomB )
{
return false;
}
if( rightA < leftB )
{
return false;
}
if( leftA > rightB )
{
return false;
}
//If none of the sides from A are outside B
return true;
}
This is the collision detection function itself.
void Player::move()
{
//Activate Gravity
yVel++;
inAir = true;
//When terminal velocity is reached(in free fall)
if(yVel > 15)
{
yVel = 15;
}
if(box.y > SCREEN_HEIGHT)
{
box.y = 0;
}
box.y += yVel;
for(int i=0; i <= 7; i++)
{
if(check_collision(box, wallBox))
{
box.y -= yVel;
yVel = 0;
inAir = false;
}
}
box.x += xVel;
for(int i=0; i <= 7; i++)
{
if(check_collision(box, wallBox))
{
box.x -=xVel;
}
}
if (box.x < -16 && xVel < 0)
{
box.x = SCREEN_WIDTH + playerClip[ 0 ].x - 8;
}
if (box.x > SCREEN_WIDTH - 16 && xVel > 0)
{
box.x = -16 + playerClip[ 0 ].x;
}
}
This is the function to move the player and handle basic mechanics.