首页 > 解决方案 > c# - 如何使用Loop来验证一个对象是否在c#WF中与另一个对象Bounds绑定Intersets?

问题描述

我如何将这一系列 if 转换为循环?

我正在制作Windows形式的2D游戏,我想检查5颗子弹中的一颗是否击中了5个敌人中的一个,但我想知道哪个子弹击中了哪个敌人!(我知道如何做到这一点的逻辑,但我只想用循环而不是用 25 if 来做)谢谢!

if (bulletOne.Bounds.IntersectsWith(enemyOne.Bounds) || bulletTwo.Bounds.IntersectsWith(enemyOne.Bounds) || bulletThree.Bounds.IntersectsWith(enemyOne.Bounds) || bulletFour.Bounds.IntersectsWith(enemyOne.Bounds) || bulletFive.Bounds.IntersectsWith(enemyOne.Bounds))
{
    enemyOne.Left = rnd.Next(1300, 1400);
}
if (bulletOne.Bounds.IntersectsWith(enemyTwo.Bounds) || bulletTwo.Bounds.IntersectsWith(enemyTwo.Bounds) || bulletThree.Bounds.IntersectsWith(enemyTwo.Bounds) || bulletFour.Bounds.IntersectsWith(enemyTwo.Bounds) || bulletFive.Bounds.IntersectsWith(enemyTwo.Bounds))
{
    enemyTwo.Left = rnd.Next(1300, 1400);
}
if (bulletOne.Bounds.IntersectsWith(enemyThree.Bounds) || bulletTwo.Bounds.IntersectsWith(enemyThree.Bounds) || bulletThree.Bounds.IntersectsWith(enemyThree.Bounds) || bulletFour.Bounds.IntersectsWith(enemyThree.Bounds) || bulletFive.Bounds.IntersectsWith(enemyThree.Bounds))
{
    enemyThree.Left = rnd.Next(1300, 1400);
}
if (bulletOne.Bounds.IntersectsWith(enemyFour.Bounds) || bulletTwo.Bounds.IntersectsWith(enemyFour.Bounds) || bulletThree.Bounds.IntersectsWith(enemyFour.Bounds) || bulletFour.Bounds.IntersectsWith(enemyFour.Bounds) || bulletFive.Bounds.IntersectsWith(enemyFour.Bounds))
{
    enemyFour.Left = rnd.Next(1300, 1400);
}
if (bulletOne.Bounds.IntersectsWith(enemyFive.Bounds) || bulletTwo.Bounds.IntersectsWith(enemyFive.Bounds) || bulletThree.Bounds.IntersectsWith(enemyFive.Bounds) || bulletFour.Bounds.IntersectsWith(enemyFive.Bounds) || bulletFive.Bounds.IntersectsWith(enemyFive.Bounds))
{
    enemyFive.Left = rnd.Next(1300, 1400);
}

标签: c#wpf2d

解决方案


尝试将子弹和敌人放在一个列表中,然后循环遍历该列表。这样,您可以让所有子弹在一个循环中检查所有敌人。

但是为了把它们放在一个列表中,你应该使用类,这样你就可以用它们制作一个对象,多次调用它们。

例如:

//note: 'Enemy' and 'Bullet' are class names, so they'll need to be defined in a seperate class
List<Enemy> enemies = new List<Enemy>();
List<Bullet> bullets = new List<Bullet>();

//fill your lists in the way you want them to spawn, example below:
bullets.Add(new Bullet(/*place your bullet variables here*/));
enemies.Add(new Enemy(/*place your enemy variables here*/));

//loop
foreach (Bullet b in bullets)
{
    foreach (Enemy e in enemies)
    {
        if (b.Bounds.IntersectsWith(e))
        {
            e.Left = rnd.Next(1300, 1400);
        }
    }
}

推荐阅读