Advertisement
Ember

intersect

Jul 1st, 2017
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. static Bool Intersection(const Line2D& lineA, const Line2D& lineB, Float2& result)
  2. {
  3.     // Compute the slopes
  4.     Float2 slopeA(lineA.End - lineA.Start), slopeB(lineB.End - lineB.Start);
  5.  
  6.     // Calculate the intersection offsets
  7.     Float offsetA = (-slopeA.y * (lineA.Start.x - lineB.Start.x) + slopeA.x * (lineA.Start.y - lineB.Start.y)) / (-slopeB.x * slopeA.y + slopeA.x * slopeB.y);
  8.     Float offsetB = (slopeB.x * (lineA.Start.y - lineB.Start.y) - slopeB.y * (lineA.Start.x - lineB.Start.x)) / (-slopeB.x * slopeA.y + slopeA.x * slopeB.y);
  9.  
  10.     // Find intersection point
  11.     if(offsetA >= 0 && offsetA <= 1 && offsetB >= 0 && offsetB <= 1)
  12.     {
  13.         // Assign result and return
  14.         result = lineA.Start + slopeA * offsetA;
  15.         return true;
  16.     }
  17.  
  18.     // No intersection found
  19.     return false;
  20. }
  21.  
  22. static Bool Intersection(const Ray2D& ray, const AABB2D& aabb, Float2& result)
  23. {
  24.     // The ray as a line
  25.     Line2D line;
  26.     line.Start = ray.Position;
  27.     line.End = ray.Position + ray.Direction * (Length(aabb.Position - ray.Position) + Length(aabb.HalfSize * 2));
  28.     // AABB sides
  29.     Line2D top(aabb.Position + aabb.HalfSize, aabb.Position + aabb.HalfSize * Float2(-1, 1));
  30.     Line2D left(aabb.Position - aabb.HalfSize, aabb.Position + aabb.HalfSize * Float2(1, -1));
  31.     Line2D down(aabb.Position - aabb.HalfSize, aabb.Position + aabb.HalfSize * Float2(1, -1));
  32.     Line2D right(aabb.Position - aabb.HalfSize, aabb.Position + aabb.HalfSize * Float2(1, -1));
  33.  
  34.     Float2 out;
  35.     // Check the four sides and return if one hits ¯\_(ツ)_/¯
  36.     if(Intersection(line, top, out)) { result = out; return true; }
  37.     if(Intersection(line, left, out)) { result = out; return true; }
  38.     if(Intersection(line, down, out)) { result = out; return true; }
  39.     if(Intersection(line, right, out)) { result = out; return true; }
  40.  
  41.     // No intersection
  42.     return false;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement