Ray.hx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package h2d.col;
  2. import hxd.Math;
  3. /**
  4. A raycast from the given position in a specified direction.
  5. **/
  6. class Ray {
  7. /** X position of the ray start. **/
  8. public var px : Float;
  9. /** Y position of the ray start. **/
  10. public var py : Float;
  11. /** X normal of the ray direction. **/
  12. public var lx : Float;
  13. /** Y normal of the ray direction. **/
  14. public var ly : Float;
  15. /**
  16. Create a new Ray instance.
  17. **/
  18. public inline function new() {
  19. }
  20. /**
  21. Returns a positive value if Point `p` is on the right side of the Ray axis and negative if it's on the left.
  22. **/
  23. public inline function side( p : Point ) {
  24. return lx * (p.y - py) - ly * (p.x - px);
  25. }
  26. /**
  27. Returns a new Point containing the Ray vector with specified length.
  28. **/
  29. public inline function getPoint( distance : Float ) {
  30. return new Point(px + distance * lx, py + distance * ly);
  31. }
  32. /**
  33. Returns new Point containing Ray starting position.
  34. **/
  35. public inline function getPos() {
  36. return new Point(px, py);
  37. }
  38. /**
  39. Returns new Point containing Ray direction.
  40. **/
  41. public inline function getDir() {
  42. return new Point(lx, ly);
  43. }
  44. function normalize() {
  45. var l = lx * lx + ly * ly;
  46. if( l == 1. ) return;
  47. if( l < Math.EPSILON ) l = 0 else l = Math.invSqrt(l);
  48. lx *= l;
  49. ly *= l;
  50. }
  51. /**
  52. Returns a new Ray starting at Point `p1` and pointing at Point `p2`.
  53. **/
  54. public static inline function fromPoints( p1 : Point, p2 : Point ) {
  55. var r = new Ray();
  56. r.px = p1.x;
  57. r.py = p1.y;
  58. r.lx = p2.x - p1.x;
  59. r.ly = p2.y - p1.y;
  60. r.normalize();
  61. return r;
  62. }
  63. /**
  64. Returns a new Ray at given position and direction.
  65. **/
  66. public static inline function fromValues( x, y, dx, dy ) {
  67. var r = new Ray();
  68. r.px = x;
  69. r.py = y;
  70. r.lx = dx;
  71. r.ly = dy;
  72. r.normalize();
  73. return r;
  74. }
  75. }