I've been trying all day without even a break to make different functions for horizontal and vertical collision detections, but I can't seem to get it right.
The best I could come up with is this:
Code:
bool vertical collision( SDL_Rect a , SDL_Rect b )
{
int lefta , leftb;
int righta , rightb;
int topa , topb;
int bottoma , bottomb;
lefta = a.x;
righta = a.x + a.w;
topa = a.y;
bottoma = a.y + a.h;
leftb = b.x;
rightb = b.x + b.w;
topb = b.y;
bottomb = b.y + b.h;
if( bottoma >= topb && topa <= bottomb && righta > leftb && lefta < rightb ) return true;
return false;
}
bool horizontal_collision( SDL_Rect a , SDL_Rect b )
{
int lefta , leftb;
int righta , rightb;
int topa , topb;
int bottoma , bottomb;
lefta = a.x;
righta = a.x + a.w;
topa = a.y;
bottoma = a.y + a.h;
leftb = b.x;
rightb = b.x + b.w;
topb = b.y;
bottomb = b.y + b.h;
if( righta >= leftb && lefta <= rightb && bottoma > topb && topa < bottomb ) return true;
return false;
}
As you can see they are almost identical, and the sprite goes crazy.
This is the moving function for the sprite:
Code:
void player::move( Uint32 delta_ticks , tile * tiles[] )
{
x += xvel * ( delta_ticks / 1000.f );
if( x < 0 ) x = 0;
if( x + PLAYER_WIDTH > LEVEL_WIDTH ) x = LEVEL_WIDTH - PLAYER_WIDTH;
if( horizontal_collision( box , tiles ) )
{
if( xvel > 0 ) x -= 1;
else if( xvel < 0 ) x += 1;
}
y += yvel * ( delta_ticks / 1000.f );
if( vertical_collision( box , tiles ) )
{
if( yvel >= 0 )
{
jumping = false;
yvel = 0;
y -= 1;
}
else
{
jumping = true;
}
}
yvel += gravity;
if( y > LEVEL_HEIGHT + 50 )
{
y = 0;
x = 0;
status = FACING_RIGHT;
}
box.x = x;
box.y = y;
}
( I will change y -= 1 , x -= 1 and x += 1 once I figure out how to calculate the closest distance the sprite can go to the tile. )
Once again I need the help of someone more experienced to proceed. Any help would be appreciated.
Thanks in advance.