我正在使用Three.js创建一个场景,我可以移动对象。我使用OBJMTLLoader加载对象。然而,这些物品不具有本地来源,它们仍然存储它们的原始来源。当我去移动一个物体时,物体首先移回原来的原点,然后你可以从那里移动物体。我已经找到了许多使用质心和边界框的例子,但我总是得到一些未定义的东西。任何帮助将不胜感激!!
loader.load('example.obj', 'example.mtl', function (object) {
object.position.y = -50; // I want this to be the new origin of the object
object.scale.set(scale, scale, scale);
});
然后我移动对象的代码:
function onDocumentMouseMove(event) {
event.preventDefault();
mouse.x = ( (event.clientX - container.offsetLeft) / container.clientWidth ) * 2 - 1;
mouse.y = -( (event.clientY - container.offsetTop ) / container.clientHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
if (SELECTED) {
var intersects = raycaster.intersectObject(plane);
SELECTED.position.copy(intersects[0].point.sub(offset));
return;
}
var intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
if (INTERSECTED != intersects[0].object) {
INTERSECTED = intersects[0].object;
plane.position.copy(INTERSECTED.position);
plane.lookAt(camera.position);
updateLightPosition();
}
container.style.cursor = 'pointer';
} else {
INTERSECTED = null;
container.style.cursor = 'auto';
}
}
function onDocumentMouseDown(event) {
event.preventDefault();
var vector = new THREE.Vector3(mouse.x, mouse.y, 1).unproject(camera);
raycaster.set(camera.position, vector.sub(camera.position).normalize());
if (selectingTargetPos) {
var intersects = raycaster.intersectObjects(background);
if (intersects.length > 0) {
selectedObject.light.target = new THREE.Object3D();
selectedObject.light.target.position.copy(intersects[0].point);
selectedObject.light.target.updateMatrixWorld();
selectingTargetPos = false;
container.style.cursor = 'auto';
}
} else if (selectingTargetObj) {
var intersects = raycaster.intersectObjects(objects);
if (intersects.length > 0) {
selectedObject.light.target = intersects[0].object;
selectedObject.light.target.updateMatrixWorld();
selectingTargetObj = false;
container.style.cursor = 'auto';
}
} else {
var intersects = raycaster.intersectObjects(objects, true);
if (intersects.length > 0) {
SELECTED = intersects[0].object.userData.rootObject;
selectedObject = SELECTED;
var intersects = raycaster.intersectObject(plane);
offset.copy(intersects[0].point).sub(plane.position);
container.style.cursor = 'move';
}
}
}
function onDocumentMouseUp(event) {
event.preventDefault();
SELECTED = null;
container.style.cursor = 'auto';
}
答案 0 :(得分:0)
由于对象位置基于平面并且对象已分组,因此问题出在INTERSECTED
事件的onDocumentMouseMove()
块中。
这不会被触发,因为raycaster没有递归地检查对象数组。通过将intersectObjects()
函数更改为第二个参数为true,问题将得到解决。
var intersects = raycaster.intersectObjects(objects, true);
if (intersects.length > 0) {
if (INTERSECTED != intersects[0].object) {
INTERSECTED = intersects[0].object;
plane.position.copy(INTERSECTED.position);
plane.lookAt(camera.position);
updateLightPosition();
}
container.style.cursor = 'pointer';
} else {
INTERSECTED = null;
container.style.cursor = 'auto';
}