在立方体中单击以画一条线时留点

时间:2019-01-04 11:15:39

标签: three.js

正在执行以下任务:通过单击一个多维数据集的线连接两个多维数据集,同时单击该多维数据集,然后单击另一个多维数据集,该点表示该行的起点和终点。这是代码,在此先感谢。 该代码有两个立方体,它们在单击时要用一条线彼此连接,在单击时我要在开始和结束行中表示一个点

var camera, scene, renderer, controls;
var raycaster = new THREE.Raycaster(),
    mouse = new THREE.Vector2();
var intersected, lineObjects = [],
    objects = [];

init();
animate();

function init() {

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 500);
    camera.position.set(5, 15, 10);
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(0xffffff);
    document.body.appendChild(renderer.domElement);
    window.addEventListener("mousedown", onMouseDown, false);
    controls = new THREE.OrbitControls(camera, renderer.domElement);
    var geometry = new THREE.BoxGeometry(1, 1, 1);
    var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
    var cube = new THREE.Mesh(geometry, material);
    scene.add(cube);


    var cube1 = new THREE.Mesh(geometry, material);
    cube1.position.set(2, 5, 5)
    scene.add(cube1);

}

function lineObj(pointStart, pointEnd) {
    var lineGeom = new THREE.Geometry();
    lineGeom.vertices.push(pointStart.clone());
    lineGeom.vertices.push(pointEnd.clone());
    var lineMat = new THREE.LineBasicMaterial({
        color: "red"
    });
    line = new THREE.Line(lineGeom, lineMat);
    return line;
}

function onMouseDown(event) {
    mouse.x = (event.clientX / renderer.domElement.clientWidth) * 2 - 1;
    mouse.y = -((event.clientY) / renderer.domElement.clientHeight) * 2 + 1;
    raycaster.setFromCamera(mouse, camera);
    var intersects = raycaster.intersectObjects(scene.children);
    // var intersects = raycaster.intersectObjects(scene.children,true);
    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 = [];
        }
    }
}

function animate() {
    requestAnimationFrame(animate);

    render();
}

function render() {
    renderer.render(scene, camera);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

0 个答案:

没有答案