C++ と SDL で 2 つの rect 間の衝突を計算するにはどうすればよいですか? また、プレーヤーがこの rect を通過できないようにするには (つまり、一方の rect がもう一方の rectを通過できないようにする) にはどうすればよいですか?
プレーヤーを停止すると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;
}