c# – 以优雅的方式使用多态进行碰撞检测

前端之家收集整理的这篇文章主要介绍了c# – 以优雅的方式使用多态进行碰撞检测前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试设置一些简单的2D形状,可以使用鼠标在窗口周围拖动.我想让形状在我将其拖入另一个时记录碰撞.我有一个界面.
  1. interface ICollidable
  2. {
  3. bool CollidedWith(Shape other);
  4. }

然后我有一个抽象类Shape实现上面的接口.

  1. abstract class Shape : ICollidable
  2. {
  3. protected bool IsPicked { private set; get; }
  4. protected Form1 Form { private set; get; }
  5.  
  6. protected int X { set; get; } // Usually top left X,Y corner point
  7. protected int Y { set; get; } // Used for drawing using the Graphics object
  8.  
  9. protected int CenterX { set; get; } // The center X point of the shape
  10. protected int CenterY { set; get; } // The center X point of the shape
  11.  
  12. public Shape(Form1 f,int x,int y)
  13. {
  14. Form = f;
  15. X = x; Y = y;
  16. Form.MouseDown += new MouseEventHandler(form_MouseDown);
  17. Form.MouseMove += new MouseEventHandler(Form_MouseMove);
  18. Form.MouseUp += new MouseEventHandler(Form_MouseUp);
  19. }
  20.  
  21. void Form_MouseMove(object sender,MouseEventArgs e)
  22. {
  23. if(IsPicked)
  24. Update(e.Location);
  25. }
  26.  
  27. void Form_MouseUp(object sender,MouseEventArgs e)
  28. {
  29. IsPicked = false;
  30. }
  31.  
  32. void form_MouseDown(object sender,MouseEventArgs e)
  33. {
  34. if (MouseInside(e.Location))
  35. IsPicked = true;
  36. }
  37.  
  38. protected abstract bool MouseInside(Point point);
  39. protected abstract void Update(Point point);
  40. public abstract void Draw(Graphics g);
  41. public abstract bool CollidedWith(Shape other);
  42. }

然后我有十个具体的类Circle,Square,Rectangle等,它们扩展了Shape类并实现了抽象方法.
我想做的是想出一些oop干净而优雅的方法来进行爆炸检测,而不是在CollidedWith方法中有一大块if语句,例如

  1. public bool CollidedWith(Shape other)
  2. {
  3. if(other is Square)
  4. {
  5. // Code to detect shape against a square
  6. }
  7. else if(other is Triangle)
  8. {
  9. // Code to detect shape against a triangle
  10. }
  11. else if(other is Circle)
  12. {
  13. // Code to detect shape against a circle
  14. }
  15. ... // Lots more if statements
  16. }

有没有人有任何想法.这是我以前想过的一个问题,但现在才开始实践.

解决方法

碰撞检测是否是“特定于形状”,对于每个排列都有不同的实现
  1. Circle vs. Other Circle
  2. Circle vs. Other Square
  3. Circle vs. Other Triangle
  4. Square vs. Other Circle
  5. ...

听起来你正在尝试创建一个包含所有可能性的矩阵,但如果你想出10个新形状,总共20个,你有400个可能性.

相反,我会尝试在您的抽象类中提出一个通用的Shape.Overlaps(Shape other)方法来满足所有这些方法.

如果这只是2D几何,那么如果要弄清楚任何形状的边路径是否相交都应该是微不足道的.

猜你在找的C#相关文章