点击改变点的位置
平面上的3个点构成三角形ABC,点P可用向量表示为:
\[P = A + u\left( {C - A} \right) + v\left( {B - A} \right)\]点P是否在三角形ABC内部,判定条件为:
\[\left\{ \begin{gathered} u \geqslant 0 \hfill \\ v \geqslant 0 \hfill \\ u + v \leqslant 1 \hfill \\ \end{gathered} \right.\]用x表示向量差X-A,可将点P的向量表示等式转化为:
\[p = uc + vb\]等式两边同时点乘c或b,得到方程组:
\[\left\{ \begin{gathered} p \cdot c = u\left( {c \cdot c} \right) + v\left( {b \cdot c} \right) \hfill \\ p \cdot b = u\left( {c \cdot b} \right) + v\left( {b \cdot b} \right) \hfill \\ \end{gathered} \right.\]解方程组得:
\[u = \frac{{\left( {p \cdot c} \right)\left( {b \cdot b} \right) - \left( {b \cdot c} \right)\left( {p \cdot b} \right)}}{{\left( {c \cdot c} \right)\left( {b \cdot b} \right) - \left( {b \cdot c} \right)\left( {b \cdot c} \right)}}\] \[v = \frac{{\left( {p \cdot b} \right)\left( {c \cdot c} \right) - \left( {p \cdot c} \right)\left( {c \cdot b} \right)}}{{\left( {c \cdot c} \right)\left( {b \cdot b} \right) - \left( {b \cdot c} \right)\left( {b \cdot c} \right)}}\]这样就可以使用各点的坐标计算向量a、b、c和p,进而判断点P是否在三角形ABC内部。
参考:https://observablehq.com/@kelleyvanevert/2d-point-in-triangle-test