I am trying to set up some simple 2D shapes which can be dragged about the window using the mouse. I want the shapes to register a collision when I drag one into another. I have an interface.
interface ICollidable
{
bool CollidedWith(Shape other);
}
I then have an abstract class Shape that implements the above interface.
abstract class Shape : ICollidable
{
protected bool IsPicked { private set; get; }
protected Form1 Form { private set; get; }
protected int X { set; get; } // Usually top left X, Y corner point
protected int Y { set; get; } // Used for drawing using the Graphics object
protected int CenterX { set; get; } // The center X point of the shape
protected int CenterY { set; get; } // The center X point of the shape
public Shape(Form1 f, int x, int y)
{
Form = f;
X = x; Y = y;
Form.MouseDown += new MouseEventHandler(form_MouseDown);
Form.MouseMove += new MouseEventHandler(Form_MouseMove);
Form.MouseUp += new MouseEventHandler(Form_MouseUp);
}
void Form_MouseMove(object sender, MouseEventArgs e)
{
if(IsPicked)
Update(e.Location);
}
void Form_MouseUp(object sender, MouseEventArgs e)
{
IsPicked = false;
}
void form_MouseDown(object sender, MouseEventArgs e)
{
if (MouseInside(e.Location))
IsPicked = true;
}
protected abstract bool MouseInside(Point point);
protected abstract void Update(Point point);
public abstract void Draw(Graphics g);
public abstract bool CollidedWith(Shape other);
}
I then have ten concrete classes Circle, Square, Rectangle etc that extend the Shape class and implement the abstract methods. What I would like to do is come up with some oop clean and elegant way to do the collosion detection instead having a large block of if statements in the CollidedWith method such is
public bool CollidedWith(Shape other)
{
if(other is Square)
{
// Code to detect shape against a square
}
else if(other is Triangle)
{
// Code to detect shape against a triangle
}
else if(other is Circle)
{
// Code to detect shape against a circle
}
... // Lots more if statements
}
Has anyone any ideas. It's a problem I've thought about before but am only putting into practice now.