两个矩形在我认为应该不相交的时候

问题描述 投票:1回答:1

我有一个敌人矩形

public void Update(GameTime gameTime)
{
  enemyRectangle = new Rectangle((int)enemyPosition.X, (int)enemyPosition.Y, enemyTexture.Width, enemyTexture.Height);
 ...

我有一个foreach循环,遍历一个矩形列表和一个检查这两个矩形是否相交的方法,该方法将返回一个布尔值。

foreach (Bounds bounds in bounds.boundsList)
{
  if (bounds.EnemyWallIntersects(testEnemy.enemyRectangle, bounds.CurrentRectangle))
   {
     testEnemy.isEnemyCurrentlyColliding = true;
   }
   testEnemy.isEnemyCurrentlyColliding = false;
 }          

我确定这些矩形应该相交,但是我不知道现在正在发生什么。我已经使用了一个断点,并且该矩形旨在与到达与敌人矩形相同的X和Y的点相交。

这是“ EnemyWallIntersects”方法。

 public bool EnemyWallIntersects(Rectangle rect1, Rectangle rect2)
 {
   if (rect1.Intersects(rect2))
   {
     return true;
   }
   else
     return false;
 }
c# xna monogame
1个回答
1
投票

您的testEnemy.isEnemyCurrentlyColliding = false;在设置testEnemy.isEnemyCurrentlyColliding = true;之后立即发生,没有其他语句,因此它将始终设置为false。

此外,请记住,这是一个foreach循环,因此列表中的下一项将再次覆盖testEnemy.isEnemyCurrentlyColliding。如果只需要检查其中一项结果是否为真,则建议使用break,它将结束当前的foreach循环。

例如:

foreach (Bounds bounds in bounds.boundsList)
    {
        if (bounds.EnemyWallIntersects(testEnemy.enemyRectangle, bounds.CurrentRectangle))
        {
            testEnemy.isEnemyCurrentlyColliding = true;
            break;
        }
        else
        {
            testEnemy.isEnemyCurrentlyColliding = false;
        }
    }         
© www.soinside.com 2019 - 2024. All rights reserved.