1

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

kk-dev11
  • 2,654
  • 5
  • 37
  • 48
  • do you see any errors in your browser's console in these cases? – Ben McCormick Jan 27 '13 at 02:17
  • @ben336 no, I don't see any errors. I analysed the values of points array. There I could notice this. Pn[256,156], Pn+1[260,159] and the current point was [258,157]. In this case the line just went through. – kk-dev11 Jan 27 '13 at 02:21
  • I think you want to check whether each line segment hits the point, rather than merely the points making up the line segment. What you do may work as long as your points are very closely spaced, but wouldn't if they are far apart. – yiding Jan 27 '13 at 02:27
  • @yiding yes. I also guess the same. The distance between two points varies from 2 to 4. Therefore sometimes it doesn't work. It would be really greatful if you could show me how to check whether each line segment hits the point? Thanks. – kk-dev11 Jan 27 '13 at 02:47

2 Answers2

2

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

Edgard Leal
  • 2,592
  • 26
  • 30
-1

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

Sitepor500.com.br
  • 388
  • 1
  • 5
  • 11