# Collision between a player and a solid block C++ SDL2

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

• Have you tried moving back the player to the edge of the box instead? If your player is moving more than a pixel a frame, then it won't work if you move the player back just 1 pixel. Commented Apr 11, 2020 at 12:32
• There is a built in function for rectangle collision check wiki.libsdl.org/SDL_HasIntersection Commented Apr 14, 2020 at 13:04

Create a new rect and initialize it with the dimensions of of your player(you named it Sprite) and make the new rect move with your player and check if the collision box of the player Colides with the solid object(Sprite1) and. Check out lazyfoo´s tutorial: https://lazyfoo.net/tutorials/SDL/27_collision_detection/index.php

    SDL_Rect r2 = Sprite1->GetRect();
if (CKeyboard::Get()->GetKey(SDL_SCANCODE_LEFT))
{
Vel.x -= 1.0f;
}
else if (CKeyboard::Get()->GetKey(SDL_SCANCODE_RIGHT))
{
Vel.x += 1.0f;
}

Position.x += Vel.x;
Collisionbox.x = Position.x;

if (Collision::Get()->Checkcollision(Collisionbox, r2))
{
Position.x -= Vel.x;
Collisionbox.x = Position.x;
}

if (CKeyboard::Get()->GetKey(SDL_SCANCODE_UP))
{
Vel.y -= 1.0f;
}
else if (CKeyboard::Get()->GetKey(SDL_SCANCODE_DOWN))
{
Vel.y += 1.0f;
Vel.y += 1.0f;
}

Position.y += Vel.y;
Collisionbox.y = Position.y;

if (Collision::Get()->Checkcollision(Collisionbox, r2))
{
Position.y -= Vel.y;
Collisionbox.y = Position.y;
}


I didn't test the code but it should work. If you'll still have trouble check out lazyfoo's tutorial about collision as I said :P.

I hope this helps