Check if a point goes through a line

385 Views Asked by At

I am programming a game in HTML5 canvas. If a line touches any point of its own or opponents line, that line stops moving. The Function I wrote follows below.

function hasPoints(x, y) {
  for (var i = 0; i < points.length; i++) {

    if (Math.abs(points[i][0] - x) < 2 && Math.abs(points[i][1] - y) < 2) {
        return true;
        break;
    }
  }
  return false;
}

//check if this point crosses other players' points
if (hasPoints(p1.x,p1.y) || canPlay==false) {
    clearLoop();
}else{
    context.fillStyle = "green";
    context.fillRect(p1.x,p1.y, 5,5);
    addPoints(p1.x,p1.y);       
    sendMyPoints();     
    loopTimer = setTimeout('drawLine()', 50);
}

It works most of the time. But in some special case(As you can see in the picture below) it simply fails to return false.

Could anyone help me to improve this function, so that it works flawless?

LineCrash

2

There are 2 best solutions below

0
On

Do not use dots, use vectors. An array of vectors. To find out if a point is in contact with a line (vector) Just mount a triangle with two points and the point vector analysis, if the area of the triangle is near zero (sets a limit), then this contact.

y1 x1 1
y2 x2 1 = (y1*x2*1)+(x1*1*y3)+(1*y2*x3)-(x1*y2*1)-(y1*1*x3)-(1*x2*y3)
y3 x3 1
the result should be close to zero (0.012121 ...)
This a way to discovery if a line is align in direction of a target
http://en.wikipedia.org/wiki/Determinant

0
On

Use math's expression to vectors then you can check if the vectors cross thenselves