c# - 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);
}
解决方案
尝试将子弹和敌人放在一个列表中,然后循环遍历该列表。这样,您可以让所有子弹在一个循环中检查所有敌人。
但是为了把它们放在一个列表中,你应该使用类,这样你就可以用它们制作一个对象,多次调用它们。
例如:
//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);
}
}
}
推荐阅读
- javascript - 如何预防
导出 javascript DataTable 时显示 - android - FT232R 设备的 USB 串口的 Android requestWait 没有被阻塞
- python-3.x - 多页上的 Tkinter 串行数据
- shell - 杀死一个 Docker 容器
- c# - 给定从 0 开始的字符串绝对索引,确定从 1 开始的行号和列号(C#)
- api - 哪个聊天api的搜索功能好?
- arrays - 如何将一列数组转换为Spark中每个数组之和的列?
- apache-spark - JDBC - cassandra sparksql 连接器可以在查询工具(即 Tableau/Alteryx/Sqlclient)中加入吗?
- java - 如何在 Rxjava 中按键合并两个 Observable?
- react-native - 不同屏幕之间的“react-navigation”,出现 500 错误