问题
在A模型中添加B模型 B模型的position是我通过射线点击A模型获取到的point的位置,现在B模型的位置不是如我所意,偏差严重,排查后,应该是相对位置发生了变化,本来相对于整个场景得到的位置,现在添加到A模型中,相对位置就是A模型了,应该将其本相对场景的坐标转换成相对于父对象的坐标。
思路
-
先计算出模型的几何中心或者相对模型的其他特定点进行定位
代码
function attachPoint(object, intersects) {
// 创建一个红色球体作为红点
const radius = 0.1;
const geometry = new THREE.SphereGeometry(radius);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const redDot = new THREE.Mesh(geometry, material);
redDot.name = '吸附点';
let currentObject = null;
if (object.parent.type == "Scene") {
currentObject = object
} else {
currentObject = object.parent
}
var redDotPosition = intersects[0].point.clone();
redDot.position.copy(redDotPosition);
// 在世界坐标系下获取点的位置
currentObject.updateMatrixWorld(); // 更新到世界坐标系下
currentObject.worldToLocal(redDot.position); // 转换到局部坐标系
currentObject.add(redDot)
}