three.js如何用mousedown事件绘制线条

时间:2016-11-02 09:05:51

标签: javascript three.js click

我已经尝试了很多方法来完成这个效果,我想绘制一行鼠标按下事件,我已经看到了很多其他问题,但对它没有任何想法,到目前为止我使用的是Ray caster方法的intersectObjects()并得到点击的位置,但我不知道如何,希望有人给我建议,非常感谢。 以下是我的代码的一部分:

event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = -( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;  
var raycaster=new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
var intersects = raycaster.intersectObjects(objects,true);
console.log(intersects[0].point);//type of intersects[0] is object,one of attribute is point?

昨天我写了一些代码并完成了我的部分工作。以下是一些代码:

 var clickCount = 0;//initial value
 clickCount = clickCount+1;
 if(intersects.length>0)
 {
     switch(clickCount)
     {
         case 1:
                var startPoint=intersects[0].point;//store the first intersect point when the first click
                break;
    case 2:
                var endPoint =intersects[0].point;//store the second intersect point when the second click
                break;
     }
  }


clickCount=1;
var geometry = new THREE.Geometry();
material = new THREE.LineBasicMaterial({color:0xffffff,linewidth:2});
geometry.vertices.push(startPoint);
geometry.vertices.push(endPoint);
line = new THREE.Line(geometry, material);
scene.add(line);

但这不是我想要的最终效果。这个线段是从矢量(0,0,0)设置的所有光线。这是截图: the red line are what i want and the white lines are real

红线是我想要实现的效果。任何人都能找出原因吗?非常感谢。

1 个答案:

答案 0 :(得分:1)

最好记住第一个点击的对象,然后在下一次点击时检查,如果它是同一个对象或另一个对象,如果它是另一个对象,则绘制他们之间的界限。

m := f.(map[string]interface{})

并在事件处理程序中:

var intersected, lineObjects = [],
objects = [];
. . .

我做了jsfiddle例子。查看 if (intersects.length > 0) { var found = intersects[0].object; if (found != intersected) { if (lineObjects.length > 0) { var line = lineObj(lineObjects[0].position, found.position); scene.add(line); lineObjects[0].material.color.setHex(lineObjects[0].userData.oldColor); intersected = null; lineObjects = []; } else { found.userData.oldColor = found.material.color.getHex(); found.material.color.set(0x00FF00); intersected = found; lineObjects.push(found); } } else { found.material.color.setHex(found.userData.oldColor); intersected = null; lineObjects = []; } } 函数。我上面描述的所有内容都在那里。