c# – 以优雅的方式使用多态进行碰撞检测
发布时间:2020-12-15 08:40:12 所属栏目:百科 来源:网络整理
导读:我正在尝试设置一些简单的2D形状,可以使用鼠标在窗口周围拖动.我想让形状在我将其拖入另一个时记录碰撞.我有一个界面. interface ICollidable{ bool CollidedWith(Shape other);} 然后我有一个抽象类Shape实现上面的接口. abstract class Shape : ICollidabl
|
我正在尝试设置一些简单的2D形状,可以使用鼠标在窗口周围拖动.我想让形状在我将其拖入另一个时记录碰撞.我有一个界面.
interface ICollidable
{
bool CollidedWith(Shape other);
}
然后我有一个抽象类Shape实现上面的接口. 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);
}
然后我有十个具体的类Circle,Square,Rectangle等,它们扩展了Shape类并实现了抽象方法. 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
}
有没有人有任何想法.这是我以前想过的一个问题,但现在才开始实践. 解决方法
碰撞检测是否是“特定于形状”,对于每个排列都有不同的实现
Circle vs. Other Circle Circle vs. Other Square Circle vs. Other Triangle Square vs. Other Circle ... 听起来你正在尝试创建一个包含所有可能性的矩阵,但如果你想出10个新形状,总共20个,你有400个可能性. 相反,我会尝试在您的抽象类中提出一个通用的Shape.Overlaps(Shape other)方法来满足所有这些方法. 如果这只是2D几何,那么如果要弄清楚任何形状的边路径是否相交都应该是微不足道的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
