c# - How to check rectangle collision on a line -


i have line drawn 2 rectangles, spanning xpos, ypos xpos2, ypos2. i'm trying detect if rectangle (stored in 4 arrays of x/y pos , random speed in 2 directions) collides line.

i've tried (vector2.distance(new vector2(xpos + 13, ypos + 13), new vector2(enx[index], eny[index])) + vector2.distance(new vector2(xpos2 + 13, ypos2 + 13), new vector2(enx[index], eny[index])) == vector2.distance(new vector2(xpos + 13, ypos + 13), new vector2(xpos2 + 13, ypos2 + 13))) in if statement, doesn't work.

edit: i've tried

        m = (ypos2 + 13 - ypos + 13) / (xpos2 + 13 - xpos + 13);         b = ((m * xpos2 + 13) - ypos2 + 13);         if (eny[index] == m * enx[index] + b) 

where xpos/2 , ypos/2 line starting points. enx[] , eny[] "enemy" x , y positions, i'm trying check if they're hitting line.

i assume have rectangle's corner positions 2d vectors:

vector2[] corners; 

the rectangle intersects line if 2 corner points lie on opposite side of line. evaluate side, need line's normal (the slope approach tried may fail vertical lines):

vector2 normal = new vector2d(ypos2 - ypos, xpos - xpos2); 

we can use sign of dot product evaluate side:

vector2 linestart = new vector2(xpos, ypos); //we don't know yet on side of line rectangle lies float rectangleside = 0; foreach(vector2 corner in corners) {     //cornerside positive if corner on side normal points to,     //zero if corner on line, , negative otherwise     float cornerside = vector2.dot(corner - linestart, normal);     if(rectangleside == 0)         //first evaluated corner or previous corners lie on line         rectangleside = cornerside;     else         if(cornerside != 0 && //ignore corners on line           (cornerside > 0) != (rectangleside > 0)) //different sides              return true; //rectangle intersects line } return false; //rectangle not intersect line 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -