基于上周对《重心计算》的学习,想到可以用有向面积设计内外检测函数。
花费十分钟了解向量积定义后,注意到
用一个
现有一个
只要先计算得
这样子就成功把
学习内外检测函数知识并思考发现,如果用
据此可以设计内外函数了。
出于时间考虑,编码的思维过程来不及写了,直接贴出最后用上的代码
/**
* 三角形图元
* @param {vec3} pos1 三角形顶点1
* @param {vec3} pos2 三角形顶点2
* @param {vec3} pos3 三角形顶点3
*/
function Primitive(pos1, pos2, pos3) {
this.calcNormal = function () {
var v12 = vec3.sub(vec3.create(), this.pos2, this.pos1);
var v13 = vec3.sub(vec3.create(), this.pos3, this.pos1);
return vec3.cross(vec3.create(), v12, v13);
}
/**
* 判断点是否在三角形内
* 尽管可能有性能问题 但是为了语义清晰 使用面向对象
* @param {*} vec
*/
this.inside = (x, y) => {
var vec = vec3.fromValues(x, y, 0);
var v12 = vec3.sub(vec3.create(), this.pos2, this.pos1);
var v23 = vec3.sub(vec3.create(), this.pos3, this.pos2);
var v31 = vec3.sub(vec3.create(), this.pos1, this.pos3);
var v1p = vec3.sub(vec3.create(), vec, this.pos1);
var v2p = vec3.sub(vec3.create(), vec, this.pos2);
var v3p = vec3.sub(vec3.create(), vec, this.pos3);
var cross1 = vec3.cross(vec3.create(), v12, v1p);
var cross2 = vec3.cross(vec3.create(), v23, v2p);
var cross3 = vec3.cross(vec3.create(), v31, v3p);
return vec3.dot(cross1, cross2) > 0 && vec3.dot(cross1, cross3) > 0;
}
this.pos1 = pos1;
this.pos2 = pos2;
this.pos3 = pos3;
this.normal = this.calcNormal();
}
评论区
评论列表
正在加载评论...