I am trying to implement an efficient collision detection between a line joining two points and a bitmap mask.
Example:
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.