Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Get collision of ray (x1,y1)->(x2,y2)
- // with rectangle (x3,y3)->(x4,y4).
- Collision getCollision(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
- //A struct to hold our collision information.
- Collision c;
- c.exists=0;
- //Remove collision if we're looking the wrong way.
- 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)){
- return c;
- }
- //Calculate slope and y-intersept.
- double m = (y2 - y1) / (x2 - x1);
- double b = y1 - m * x1;
- //Calculate 4 intersection points.
- double xa = (y3 - b) / m;
- double ya = m * x3 + b;
- double xb = (y4 - b) / m;
- double yb = m * x4 + b;
- //Calculate distances.
- double dxa = pow(xa - x1, 2) + pow(y3 - y1, 2);
- double dya = pow(ya - y1, 2) + pow(x3 - x1, 2);
- double dxb = pow(xb - x1, 2) + pow(y4 - y1, 2);
- double dyb = pow(yb - y1, 2) + pow(x4 - x1, 2);
- //Get closest intersection point.
- double dist = INFINITY;
- if (xa >= x3 && xa <= x4 && dxa < dist) {
- dist = dxa;
- c.x = xa;
- c.y = y3;
- c.exists=1;
- }
- if (xb >= x3 && xb <= x4 && dya < dist) {
- dist = dya;
- c.y = ya;
- c.x = x3;
- c.exists=1;
- }
- if (ya >= y3 && ya <= y4 && dxb < dist) {
- dist = dxb;
- c.x = xb;
- c.y = y4;
- c.exists=1;
- }
- if (yb >= y3 && yb <= y4 && dyb < dist) {
- dist = dyb;
- c.y = yb;
- c.x = x4;
- c.exists=1;
- }
- //Return the collision information.
- return c;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement