Line2.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. namespace BansheeEngine
  3. {
  4. /** @addtogroup Math
  5. * @{
  6. */
  7. /// <summary>
  8. /// A line in 2D space represented with an origin and direction.
  9. /// </summary>
  10. public class Line2
  11. {
  12. public Line2() { }
  13. public Line2(Vector2 origin, Vector2 direction)
  14. {
  15. this.origin = origin;
  16. this.direction = direction;
  17. }
  18. /// <summary>
  19. /// Line/Line intersection, returns boolean result and distance to intersection point.
  20. /// </summary>
  21. /// <returns>True on intersection, false otherwise.</returns>
  22. public bool Intersects(Line2 rhs, out float t)
  23. {
  24. t = 0.0f;
  25. Vector2 diff = rhs.origin - origin;
  26. float rxs = Vector2.Cross(direction, rhs.direction);
  27. float qpxr = Vector2.Cross(diff, direction);
  28. if (rxs == 0.0f && qpxr == 0.0f)
  29. return false;
  30. if (rxs == 0.0f && qpxr != 0.0f)
  31. return false;
  32. t = Vector2.Cross(diff, rhs.direction) / rxs;
  33. var u = Vector2.Cross(diff, direction) / rxs;
  34. if (rxs != 0.0f && (0 <= t && t <= 1) && (0 <= u && u <= 1))
  35. return true;
  36. return false;
  37. }
  38. public Vector2 origin = new Vector2(0.0f, 0.0f);
  39. public Vector2 direction = new Vector2(0.0f, 1.0f);
  40. }
  41. /** @} */
  42. }