正如标题所暗示的,我遇到了一个switch
语句未能检查循环i
内的变量for
某个值的问题。下面的布尔函数模拟两个精灵之间的定向边界框碰撞,i
变量代表定向边界框的每个面。但是,当函数返回时false
,i
仅在值0
和处检查1
,而当函数返回时true
,i
仅在值2
和处检查3
。
我不知道是for
循环还是switch
语句导致了这个错误,我已经仔细检查了碰撞是否在定向边界框的所有面上都有效,我可以确认它确实完美无缺。任何形式的帮助将不胜感激!
碰撞.cpp:
bool Collision::orientedBoundingBoxTest(const sf::Sprite &object1, const sf::Sprite &object2, int object1Width, int object1Height, int object2Width, int object2Height)
{
/*Variables assigned and declared here*/
for (int i = 0; i < 4; i++)
{
float faceX = collisionObject1.getPoint(i).x - collisionObject1.getPoint((i + 1) % 4).x;
float faceY = collisionObject1.getPoint(i).y - collisionObject1.getPoint((i + 1) % 4).y;
float perpendicularAxisX = -faceY;
float perpendicularAxisY = faceX;
float normalizedAxisLength = sqrt(perpendicularAxisX * perpendicularAxisX + perpendicularAxisY * perpendicularAxisY);
perpendicularAxisX /= normalizedAxisLength;
perpendicularAxisY /= normalizedAxisLength;
float object1Min = std::numeric_limits<float>::max(), object1Max = -object1Min;
float object2Min = std::numeric_limits<float>::max(), object2Max = -object2Min;
for(int j = 0; j < 4; j++)
{
float object1Projection = (perpendicularAxisX * (collisionObject1.getPoint(j % 4).x + collisionObject1.getPosition().x) + perpendicularAxisY * (collisionObject1.getPoint(j % 4).y + collisionObject1.getPosition().y)) / (perpendicularAxisX * perpendicularAxisX + perpendicularAxisY * perpendicularAxisY);
object1Min = min(object1Projection, object1Min);
object1Max = max(object1Projection, object1Max);
}
for(int j = 0; j < 4; j++)
{
float object2Projection = (perpendicularAxisX * (collisionObject2.getPoint(j % 4).x + collisionObject2.getPosition().x) + perpendicularAxisY * (collisionObject2.getPoint(j % 4).y + collisionObject2.getPosition().y)) / (perpendicularAxisX * perpendicularAxisX + perpendicularAxisY * perpendicularAxisY);
object2Min = min(object2Projection, object2Min);
object2Max = max(object2Projection, object2Max);
}
switch (i) //Switch statement failing to check "i" variable at certain values
{
case 0:
deltaY = -(object1Max - object2Min);
break;
case 1:
deltaX = object1Min - object2Max;
break;
case 2:
deltaY = object1Min - object2Max;
break;
case 3:
deltaX = -(object1Max - object2Min);
break;
}
if (! (object1Max >= object2Min && object1Min <= object2Max))
return false;
}
return true;
}
引擎.cpp:
void Engine::physics(sf::RenderWindow& _window)
{
for (int i = 0; i < 5; i++)
{
if (collision.orientedBoundingBoxTest(collisionArray[i].collisionObjectSprite, player.playerSprite, collisionArray[i].width, collisionArray[i].height, player.width, player.height))
{
currentCollisionObjectIndex = i;
player.hitTest = true;
break;
}
else
{
player.hitTest = false;
}
}
/*Additional code here*/
}