LINE/LINE
With this example, you'll be able to build a super-sweet sword fighting game! (Or reboot one that never got finished?)
To check if two lines are touching, we have to calculate the distance to the point of intersection:
var uA = x4-x3*y1-y3 - y4-y3*x1-x3 / y4-y3*x2-x1 - x4-x3*y2-y1; var uB = x2-x1*y1-y3 - y2-y1*x1-x3 / y4-y3*x2-x1 - x4-x3*y2-y1;
If there is a collision, uA
and uB
should both be in the range of 0-1. We test for that like this:
if uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1 return true;return false;
That's it! We can add one more feature, if desired, that will tell us the intersection point of the two lines. This might be useful if, for example, you're making a sword-fighting game and want sparks to fly where the two blades hit.
var intersectionX = x1 + uA * x2-x1;var intersectionY = y1 + uA * y2-y1;
Here's the full example:
var x1 = 0; // line controlled by mousevar y1 = 0;var x2 = 10; // fixed endvar y2 = 10; var x3 = 100; // static linevar y3 = 300;var x4 = 500;var y4 = 100; { var canvas = ; ; // make lines easier to see} { ; // set line's end to mouse coordinates x1 = mouseX; y1 = mouseY; // check for collision // if hit, change color of line var hit = ; if hit ; else ; ; // draw user-controlled line ; ;} // LINE/LINE { // calculate the distance to intersection point var uA = x4-x3*y1-y3 - y4-y3*x1-x3 / y4-y3*x2-x1 - x4-x3*y2-y1; var uB = x2-x1*y1-y3 - y2-y1*x1-x3 / y4-y3*x2-x1 - x4-x3*y2-y1; // if uA and uB are between 0-1, lines are colliding if uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1 // optionally, draw a circle where the lines meet var intersectionX = x1 + uA * x2-x1; var intersectionY = y1 + uA * y2-y1; ; ; ; return true; return false;}
Based on a tutorial by Paul Bourke, who includes code to test if the lines are parallel and coincident. Also based on this post by Ibackstrom and help from Reddit.