如何计算 C++ 和 SDL 中两个矩形之间的碰撞,以及如何让玩家无法通过这个矩形(即确保一个矩形不能通过另一个矩形)?
我知道停止玩家会是playeryvel = 0
,使玩家的 Y 速度为 0,因此他们无法通过它。我的问题是,当我想停止通过另一个矩形移动时,这将停止所有垂直移动。
我当前的代码使用了一个名为check_collision(SDL_Rect, SDL_Rect)
. 这是我的用法代码和实际功能。
// This loops through a vector, containing rects.
for (int i=0; i<MAP::wall.size(); i++)
{
std::cout << i << std::endl;
cMap.FillCustomRect(MAP::wall.at(i), 0xFFFFFF);
if (check_collision(cMap.wall.at(i), cDisplay.getPlayer(playerx, playery)))
{
exit(0); // It exits just as an example to show if there actually is a collision
}
}
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;
}