Polygons.hx 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package h2d.col;
  2. import hxd.Math;
  3. /**
  4. An abstract over an Array of `Polygon` instances that define multiple polygonal shapes that can be collision-tested against.
  5. @see `h2d.IPolygons`
  6. **/
  7. @:forward(push,remove)
  8. abstract Polygons(Array<Polygon>) from Array<Polygon> to Array<Polygon> {
  9. /**
  10. An underlying Polygon array.
  11. **/
  12. public var polygons(get, never) : Array<Polygon>;
  13. /**
  14. The amount of polygons in the Polygons instance.
  15. **/
  16. public var length(get, never) : Int;
  17. inline function get_length() return this.length;
  18. inline function get_polygons() return this;
  19. /**
  20. Create a new Polygons instance.
  21. @param polygons An optional list of polygons to use.
  22. **/
  23. public inline function new( ?polygons ) {
  24. this = polygons == null ? [] : polygons;
  25. }
  26. @:dox(hide)
  27. public inline function iterator() {
  28. return new hxd.impl.ArrayIterator(this);
  29. }
  30. /**
  31. Converts Polygons instance to Int-based IPolygons.
  32. **/
  33. public function toIPolygons( scale = 1. ) : IPolygons {
  34. return [for( p in polygons ) p.toIPolygon(scale)];
  35. }
  36. /**
  37. Returns bounding box of all Polygon instances in Polygons.
  38. @param b Optional Bounds instance to be filled. Returns new Bounds instance if `null`.
  39. **/
  40. public function getBounds( ?b : Bounds ) {
  41. if( b == null ) b = new Bounds();
  42. for( p in polygons )
  43. p.getBounds(b);
  44. return b;
  45. }
  46. /**
  47. Returns new `PolygonCollider` instance containing this Polygons.
  48. @param isConvex Use simplified collision test suited for convex polygons. Results are undefined if polygon is concave.
  49. **/
  50. public function getCollider(isConvex : Bool = false) {
  51. return new PolygonCollider(this, isConvex);
  52. }
  53. /**
  54. Tests if Point `p` is inside any of the Polygon instances in Polygons.
  55. @param p The point to test against.
  56. @param isConvex Use simplified collision test suited for convex polygons. Results are undefined if polygon is concave.
  57. **/
  58. public function contains( p : Point, isConvex = false ) {
  59. for( pl in polygons )
  60. if( pl.contains(p, isConvex) )
  61. return true;
  62. return false;
  63. }
  64. /**
  65. Optimizes all polygons and returns new Polygons instances. See [h2d.col.Polygon.optimize].
  66. **/
  67. public function optimize( epsilon : Float ) : Polygons {
  68. return [for( p in polygons ) p.optimize(epsilon)];
  69. }
  70. }