3

I am trying to implement an efficient collision detection between a line joining two points and a bitmap mask.

Example:

bitmap and two points

Currently I am using Bresenham's line drawing algorithm to draw each pixel of the line between the two points and comparing that pixel with the bitmap (If the pixel is black return true else continue drawing the line).

collision(x0,y0,x1,y1) {
  let dx = Math.abs(x1 - x0),
    dy = Math.abs(y1 - y0),
    sx = (x0 < x1) ? 1 : -1,
    sy = (y0 < y1) ? 1 : -1,
    err = dx - dy,
    e2

  // loop through line drawing
  while (!((x0 == x1) && (y0 == y1))) {
    e2 = err << 1;
    // check line point x,y against bitmap
    if (bitmap[x0][y0] == 1) {
      return 1;
    }
    if (e2 > -dy) {
      err -= dy;
      x0 += sx;
    }
    if (e2 < dx) {
      err += dx;
      y0 += sy;
    }
  }
  // If looped through whole line and not returned collision return false
  return 0
}

Is this a good/efficient approach? Or is there a set method or better approach for this problem?

Thanks in advance.

Alessi 42
  • 1,112
  • 11
  • 26
  • 3
    You should probably take this to codereview.stackexchange.com, questions about optimization are meant to be posted there. – Máté Safranka May 27 '18 at 13:42
  • 1
    Link to the code review question: https://codereview.stackexchange.com/questions/195265/line-and-bitmap-collision-detection – Alessi 42 Dec 12 '19 at 17:52

0 Answers0