xna 4.0 准备使用列表进行多重碰撞检测
我有一个对象列表,其中所有对象都有一个每次更新的边界矩形...我如何有效地在它们之间进行迭代?我认为这样检查就可以了,但是有什么想法吗?
for (int i = 0; i < birds.Count; i++)
{
for (int j = 0; j < birds.Count; j++)
{
if (j > i)
{
if (birds[j].boundingRectangle.Intersects(birds[i].boundingRectangle))
{
birds[i].tintColor = Color.Yellow;
birds[j].tintColor = Color.Yellow;
}
else
{
birds[i].tintColor = Color.White;
birds[j].tintColor = Color.White;
}
}
}
}
I have a List of objects of which all have a bounding rectangle updated everytime... How can I effectively iterate among them ? I thought that checking it like this is fine but any ideas ?
for (int i = 0; i < birds.Count; i++)
{
for (int j = 0; j < birds.Count; j++)
{
if (j > i)
{
if (birds[j].boundingRectangle.Intersects(birds[i].boundingRectangle))
{
birds[i].tintColor = Color.Yellow;
birds[j].tintColor = Color.Yellow;
}
else
{
birds[i].tintColor = Color.White;
birds[j].tintColor = Color.White;
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不明白为什么它无法检测到碰撞,代码似乎没问题。您应该输出一些显示边界矩形值的字符串,以查看它们是否正确设置,或者您是否正在执行该代码,或者您的“birds”数组是否在执行该代码的范围内存活(您可以修改副本而不是实际数组)。
至于改进,你可以这样做:
然后你可以删除
if (j > i)
(j将始终> i)。我建议的另一件事是不要在
for
语句中声明int j
。在外部声明它总是比在每个i
上实例化要好,所以:我认为如果不能使用指针,就没有更多的改进空间。无论如何,您的方法对于 2D 图形来说都很好,除非您要检查数百个对象。
PS:我相信您的问题可能适合 Game Development - SE 网站(除非您将 XNA 和边界框用于其他用途: )
I can't see there why it would fail to detect the collision, the code seems to be ok. You should output some string showing the values of the bounding rectangles to see if they're properly set, or if you are executing that code at all, or if your "birds" array survives the scope in where this code is executed (you may be modifying a copy instead of the actual array).
As for improvements, you can do:
and then you can remove the
if (j > i)
(j will always be > i).Other thing that I would recommend is not declaring
int j
in thefor
statement. It's always better to having it declared outside than instancing on everyi
, so:I don't think there is much more room for improvement there without being able to use pointers. Your method is fine for 2D graphics anyway, unless you're checking for hundreds of objects.
PS: I believe your question could fit in the Game Development - SE site (unless you're using XNA and bounding boxes for something else :P)
您的问题是,在比较矩形时,您将鸟设置为白色,即使它之前通过先前的命中检测设置为黄色,因此它可能已设置为黄色,但如果最后一次测试失败,它会再次设置回来。
如何在每帧开始时(在碰撞检测之前)将矩形设置为白色,然后如果发生碰撞,将它们设置为黄色(如果没有碰撞,则将其保留)。
Your problem is that when comparing rectangles you set the bird to white, even if it was previously set to yellow by a previous hit detection, so it may have been set to yellow, but it'll be set back again if the last test fails.
How about at the start of each frame (before collision detection) set the rectangles to white then if you get a collision set them to yellow (leaving them alone if there's no collision).