I am trying to implement a collision between a player and a solid e.g. a solid box.
bool Collision::Checkcollision(const SDL_Rect &A, const SDL_Rect &B)
{
return A.y + A.h >= B.y &&
A.y <= B.y + B.h &&
A.x <= B.x + B.w &&
A.x + A.w >= B.x;
}
if (CKeyboard::Get()->GetKey(SDL_SCANCODE_DOWN))
{
Vel.y += 1.0f;
}
if (CKeyboard::Get()->GetKey(SDL_SCANCODE_RIGHT))
{
Vel.x += 1.0f;
}
if (CKeyboard::Get()->GetKey(SDL_SCANCODE_UP))
{
Vel.y -= 1.0f;
}
if (CKeyboard::Get()->GetKey(SDL_SCANCODE_LEFT))
{
Vel.x -= 1.0f;
}
Position = Position + Vel.GetNormalized();
SDL_Rect r1 = Sprite->Get_Rect();
SDL_Rect r2 = Sprite1->Get_Rect();
if (Collision::Get()->Checkcollision(r1,r2))
{
if (Vel.x < 1.f)
{
Position.x = Position.x - 1;
Vel.x = 0;
}
if (Vel.x > 0.f)
{
Position.x = Position.x + 1;
Vel.x = 0;
}
if (Vel.y < 1.f)
{
Position.y = Position.y - 1;
Vel.y = 0;
}
if (Vel.y > 0.f)
{
Position.y= Position.y + 1;
Vel.y = 0;
}
}
The problem is I still can move through the box if i keep pressing a key. So the question is what is the best way to implement collision in SDL? Thank you in advance