以下是一个拖动示例:https://codepen.io/alexcheninfo/pen/vKkgkE。如果您将一个立方体放在另一个立方体的顶部并抓住前面的立方体,则也会拖动背面的立方体。
这里是完整的代码:
<script>
AFRAME.registerComponent('draggable', {
init() {
this.mouse = new THREE.Vector2();
this.scene = this.el.sceneEl;
this.camera = this.scene.camera;
this.obj = this.el.object3D;
this.scene.addEventListener('mousemove', e => {
this.mouse.x = (e.offsetX / this.scene.canvas.offsetWidth) * 2 - 1;
this.mouse.y = -(e.offsetY / this.scene.canvas.offsetHeight) * 2 + 1;
if (this.selected) {
let r = new THREE.Raycaster();
r.setFromCamera(this.mouse, this.camera);
let dist = this.obj.position.distanceTo(this.camera.position);
let point = r.ray.direction.multiplyScalar(dist);
this.el.setAttribute('position', `${point.x} ${point.y} ${point.z}`);
}
});
this.scene.addEventListener('mousedown', e => {
let r = new THREE.Raycaster();
r.setFromCamera(this.mouse, this.camera);
let intersected = r.intersectObject(this.el.object3D, true);
let objPos = this.el.object3D.position;
let camPos = this.camera.position;
console.log(objPos.distanceTo(camPos));
if (intersected.length) this.selected = true;
});
this.scene.addEventListener('mouseup', e => {
this.selected = undefined;
});
}
});
</script>
<a-scene>
<a-entity camera look-controls></a-entity>
<a-sky src="https://raw.githubusercontent.com/aframevr/aframe/master/examples/boilerplate/panorama/puydesancy.jpg"></a-sky>
<a-box color="tomato" position="-3 0 -10" draggable></a-box>
<a-box draggable position="3 0 -5" draggable></a-box>
</a-scene>
如何防止这种情况? (例如,只能在前面拖动立方体?)
答案 0 :(得分:2)
这是因为您放置控件的位置。你正在做许多射线到一个摄像机,而不是一个raycaster到多个对象。如果你有一个raycaster知道它相交的所有东西(它会返回按距离排序的对象),这会更容易。 http://threejs.org/docs/api/core/Raycaster.html
我将如何构建它:
draggable
组件,draggable
类或data-draggable
属性的对象相交。
<a-scene>
<a-camera>
<a-entity dragger></a-entity>
</a-camera>
<a-entity draggable></a-entity>
</a-scene>
AFRAME.registerComponent('dragger', {
init: function () {
// Configure raycaster.
this.el.setAttribute('raycaster', {
objects: '[draggable]',
// ...
});
},
tick: function () {
// Use this.el.components.raycaster.intersectedEls
}
});