判斷坐標是否落在三角型內
https://segmentfault.com/q/1010000009698222
已試過,以下這個方法可以得到正確的答案
function pointInTriangle(x0, y0, x1, y1, x2, y2, x3, y3) {
var divisor = (y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3);
var a = ((y2 - y3)*(x0 - x3) + (x3 - x2)*(y0 - y3)) / divisor;
var b = ((y3 - y1)*(x0 - x3) + (x1 - x3)*(y0 - y3)) / divisor;
var c = 1 - a - b;
return a >= 0 && a <= 1 && b >= 0 && b <= 1 && c >= 0 && c <= 1
}
公式如下
a = ((y2 - y3)*(x0 - x3) + (x3 - x2)*(y0 - y3)) / ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
b = ((y3 - y1)*(x0 - x3) + (x1 - x3)*(y0 - y3)) / ((y2 - y3)*(x1 - x3) + (x3 - x2)*(y1 - y3))
c = 1 - a - b