[英]C++ DirectX11 2d Game: Stopping enemy sprites moving over each other?
我正在使用IntersectsWith(this->boundingBox))
方法來檢測精靈與播放器之間的碰撞。 我希望能夠以某種方式使用這種方法來檢測我的敵方精靈相互碰撞,並在它們確實這樣做時確保它們不會彼此移動。
所有敵人的精靈都會跟隨玩家。
MainGame.cpp
循環遍歷向量中的每個敵人並執行更新循環:
for (auto &enemyMobsObj : this->enemyMobs)
{
enemyMobsObj->Update(tickTotal, tickDelta, timeTotal, timeDelta, windowBounds, this->ship, this->firstBoss,
this->enemyMobs, this->bullets, this->missiles, NULL, "NULL", "NULL");
}
這是我之前嘗試停止每個精靈彼此移動的方法:
EnemyMobOne ::更新:
int nextEnemy;
for (int i = 0; i < enemyMobOne.size(); i++)
{
nextEnemy = i + 1;
if (nextEnemy < enemyMobOne.size())
{
//Deal with mobs collision
if (enemyMobOne[i].boundingBox.IntersectsWith(enemyMobOne[nextEnemy].boundingBox))
{
enemyMobOne[i].position.x = enemyMobOne[nextEnemy].position.x - enemyMobOne[i].boundingBox.Width;
}
}
}
但是,這使每個敵人的精靈顯然彼此粘在一起,看起來不正確,也使它們瞬移。
有人知道正確的代碼以阻止它們相互移動嗎? 謝謝。
當您檢測到兩個碰撞對象之間的相交時,您需要決定如何抵消重疊(如我所確定的那樣)。 但是,與僅將它們“推”到一側(就像您在代碼中所做的那樣)相比,這樣做的技巧有些棘手。 可以這么說,您可能想要做的是對所施加的力施加反作用力。 基本上,您要計算最小平移量或所需最少移動量的方向,以獲取至少一個框來移出另一個框。
這比簡單地“讓我在另一個人的右邊(或者,取決於您如何設置坐標,我想)在我的另一邊”(這差不多就是您的代碼現在所做的)要復雜得多。
對於一個簡單的解決方案,只需檢查一個對撞機是否更靠近另一個對撞機的左,右,上或下。 為此,您可以簡單地獲取碰撞相交位置,並檢查該點與相對於一個對撞機的最小和最大x和y坐標之間的相對距離,然后相應地移動一個或兩個精靈。
例如:[編輯]在回顧了我以前的回答后,我意識到您需要計算方框的重疊量,這將使完成這些操作變得更加容易,如下所示:
float minX = min(sprite0.boundingBox.maxX, sprite1.boundingBox.maxX);// Minimum of the boxes' right-side points (top right and bottom right) x coordinates
float minY = min(sprite0.boundingBox.maxY, sprite1.boundingBox.maxY);// Minimum of the boxes' top-side points (top left and top right) y coordinates
float maxX = max(sprite0.boundingBox.minX, sprite1.boundingBox.minX);// Maximum of the boxes' left-side points (top left and bottom left) x coordinates
float maxY = max(sprite0.boundingBox.minY, sprite1.boundingBox.minY);// Maximum of the boxes' bottom-side points (bottom left and bottom right) y coordinates
float distHoriz = minX - maxX;// The horizontal intersection distance
float distVert = minY - maxY;// The vertical instersection distance
// If the boxes are overlapping less on the horizontal axis than the vertical axis,
// move one of the sprites (in this case, sprite0) in the opposite direction of the
// x-axis overlap
if(abs(distHoriz) < abs(distVert))
{
sprite0.x -= distHoriz;
}
// Else, move one of the sprites (again, I just decided to use sprite0 here,
// arbitrarily) in the opposite direction of the y-axis overlap
else
{
sprite0.y -= distVert;
}
為了進一步澄清(除了注釋之外),我們在這里基本上要做的是檢查重疊線之間的距離。 例如:
Box 0 x-axis xmin0|------------------|xmax0
Box 1 x-axis xmin1|----------------------|xmax1
|----|<-- Overlap (xmax0 - xmin1)
請注意,來自兩個邊界框的用於重疊的最小值是兩個最小值(xmin0和xmin1)中的最大值,用於重疊的最大值是兩個最大值(xmax0和xmax1)中的最小值。
y軸計算的工作方式完全相同。 一旦有了兩個軸,我們只需檢查一下哪個軸的絕對值較低(哪個距離更短),然后沿該距離移動以抵消相交。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.