Reputation: 2489
I'm creating a small wpf game, where I need some collision detection. I have some fish, which are drawn in expression blend, and I need to know when they collide. But I don't really know how to implement this.
I would like to use per pixel collision detection, and use the bounding rectangle as a cut-off (don't look for collision outside).
But is this at all the smartest way to implement collision detection? I have a path on each figure, is this information useful. As I see it, I don't achieve much from it, because it's not straight lines, but curved.
Any help will really be appreciated :)
Upvotes: 0
Views: 771
Reputation: 1265
This has not been tested, but try something like:
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);
}
}
Upvotes: 1