【发布时间】:2011-07-19 09:27:39
【问题描述】:
我正在创建一个小型 wpf 游戏,我需要一些碰撞检测。我有一些鱼,它们是在表情混合中绘制的,我需要知道它们何时发生碰撞。但我真的不知道如何实现这一点。
我想使用每像素碰撞检测,并使用边界矩形作为截止点(不要在外面寻找碰撞)。
但这是实现碰撞检测的最聪明的方法吗?我在每个图上都有一条路径,这些信息有用吗?在我看来,我并没有从中获得太多收获,因为它不是直线,而是曲线。
任何帮助将不胜感激:)
【问题讨论】:
我正在创建一个小型 wpf 游戏,我需要一些碰撞检测。我有一些鱼,它们是在表情混合中绘制的,我需要知道它们何时发生碰撞。但我真的不知道如何实现这一点。
我想使用每像素碰撞检测,并使用边界矩形作为截止点(不要在外面寻找碰撞)。
但这是实现碰撞检测的最聪明的方法吗?我在每个图上都有一条路径,这些信息有用吗?在我看来,我并没有从中获得太多收获,因为它不是直线,而是曲线。
任何帮助将不胜感激:)
【问题讨论】:
这还没有经过测试,但尝试类似:
public bool CollidsWith(FrameworkElement sprite1, FrameworkElement sprite2, bool pixelPerfect)
{
try
{
Rect r1 = Bounds(sprite1);
Rect r2 = Bounds(sprite2);
if (r1.IntersectsWith(r2))
{
if (!pixelPerfect)
return true;
else
{
Point pt = new Poin();
for (int x = (int)r1.Left; x < (int)r1.Right; x++)
{
for (int y = (int)r1.Top; y <(int)r1.Bottom; y++)
{
pt.X = x;
pt.Y = y;
if (VisualTreeHelper.HitTest(sprite2, pt) != null)
return true;
}
}
return false;
}
else
return false;
}
}
catch { }
return false; // we should not get here
}
public Rect Bounds(FrameworkElement sprite)
{
get
{
Point ptBottomRight = new Point(sprite.Position.X + sprite.RenderSize.Width, sprite.Position.Y + RenderSize.Height);
return new Rect(sprite.Position, ptBottomRight);
}
}
【讨论】: