判斷一個點是否在不規則的多邊形內方法 :
(1) 利用射線法 (ray casting)
說明 :
上圖 一個點固定 y 往右邊設一條線過去進入多邊形 如果 in 與 out 加起來為偶數的話就等於點不在多邊形內 如果 in 與 out 加起來為基數的話就等於點在多邊形內
但此時有個問題...如果射線剛好經過頂點呢 ? 就利用兩點式斜率判斷射線是否剛好在 polygon 的頂點上
code 如下 : < typescript >
// 使用射線法判斷
private rayCastingIsPointInPolygon(point: any): boolean {
// this.mPoints -> 多邊形的 point
let current_x = 0, current_y = 0, pre_x = 0, pre_y = 0, result_x = 0;
let inside = false;
for(let index = 0, prevIndex = this.mPoints.length - 1; index < this.mPoints.length; prevIndex = index++) {
current_x = this.mPoints[index].x;
current_y = this.mPoints[index].y;
pre_x = this.mPoints[prevIndex].x;
pre_y = this.mPoints[prevIndex].y;
// point on polygon point
if((current_x === point.x && current_y === point.y) || (pre_x === point.x && pre_y === point.y)) {
return false;
}
// 判斷目標的 y 是否於 polygon 線段內
if((current_y < point.y && pre_y >= point.y) || (current_y >= point.y && pre_y < point.y)) {
// 使用 兩點式 斜率判斷 point 射線是否經過 polygon 線段
// 公式 --> x = x1 + (y - y1) * (x2 - x1) / (y2 - y1)
result_x = current_x + (point.y - current_y) * (pre_x - current_x) / (pre_y - current_y);
// point 在 polygon 邊上
if(result_x == point.x){
return false;
}
if(result_x > point.x){
inside = !inside;
}
}
}
return inside; // 穿過
}
以上參考 :
(1) 兩點式 : https://zh.wikipedia.org/wiki/%E6%96%9C%E7%8E%87
(2) 射線法 : http://bl.ocks.org/bycoffe/5575904