Advertisement
12Me21

Untitled

May 4th, 2019
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.45 KB | None | 0 0
  1. //Get collision of ray (x1,y1)->(x2,y2)
  2. //  with rectangle (x3,y3)->(x4,y4).  
  3. Collision getCollision(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
  4.     //A struct to hold our collision information.
  5.     Collision c;
  6.     c.exists=0;
  7.    
  8.     //Remove collision if we're looking the wrong way.
  9.     if((x1<x3 && x1<x4 && x2<x1) || (x1>x3 && x1>x4 && x2>x1) || (y1<y3 && y1<y4 && y2<y1) || (y1>y3 && y1>y4 && y2>y1)){
  10.         return c;
  11.     }
  12.    
  13.     //Calculate slope and y-intersept.
  14.     double m = (y2 - y1) / (x2 - x1);
  15.     double b = y1 - m * x1;
  16.    
  17.     //Calculate 4 intersection points.
  18.     double xa = (y3 - b) / m;
  19.     double ya = m * x3 + b;
  20.     double xb = (y4 - b) / m;
  21.     double yb = m * x4 + b;
  22.    
  23.     //Calculate distances.
  24.     double dxa = pow(xa - x1, 2) + pow(y3 - y1, 2);
  25.     double dya = pow(ya - y1, 2) + pow(x3 - x1, 2);
  26.     double dxb = pow(xb - x1, 2) + pow(y4 - y1, 2);
  27.     double dyb = pow(yb - y1, 2) + pow(x4 - x1, 2);
  28.    
  29.     //Get closest intersection point.
  30.     double dist = INFINITY;
  31.    
  32.     if (xa >= x3 && xa <= x4 && dxa < dist) {
  33.         dist = dxa;
  34.         c.x = xa;
  35.         c.y = y3;
  36.         c.exists=1;
  37.     }
  38.     if (xb >= x3 && xb <= x4 && dya < dist) {
  39.         dist = dya;
  40.         c.y = ya;
  41.         c.x = x3;
  42.         c.exists=1;
  43.     }
  44.     if (ya >= y3 && ya <= y4 && dxb < dist) {
  45.         dist = dxb;
  46.         c.x = xb;
  47.         c.y = y4;
  48.         c.exists=1;
  49.     }
  50.     if (yb >= y3 && yb <= y4 && dyb < dist) {
  51.         dist = dyb;
  52.         c.y = yb;
  53.         c.x = x4;
  54.         c.exists=1;
  55.     }
  56.    
  57.     //Return the collision information.
  58.     return c;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement