在鼠标悬停时重新渲染对象

时间:2018-12-20 18:09:13

标签: three.js

我将在电子版中设置threejs编辑器,并将对其进行自定义。我正在尝试实现一个“悬停”对象以更改面孔的颜色,然后选择两个对象的两个面孔并捕捉它们(面对面)。因此,现在我实现了悬停效果,但是效果不佳:它相当随机地更新(而不是现在,当鼠标悬停时)。我在哪里错了?

function onMouseMove( event ) {

    var mouse = new THREE.Vector2(), INTERSECTED;

    event.preventDefault();

    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

    // find intersections

    var camera = editor.camera, scene = editor.scene;

    var raycaster = new THREE.Raycaster();
    raycaster.setFromCamera( mouse, camera );

    var intersects = raycaster.intersectObjects( scene.children );

    if ( intersects.length > 0 && intersects[ 0 ].object.material.emissive != undefined ) {

        if ( intersects.length > 0 ) {

            if ( INTERSECTED != intersects[ 0 ].object ) {

                if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );

                INTERSECTED = intersects[ 0 ].object;
                INTERSECTED.currentHex = INTERSECTED.material.emissive.getHex();
                INTERSECTED.material.emissive.setHex( 0xff0000 );

            }

        } else {

            if ( INTERSECTED ) INTERSECTED.material.emissive.setHex( INTERSECTED.currentHex );

            INTERSECTED = null;

        }

    }

    if ( intersects.length > 0 && intersects[ 0 ].object.material.emissive == undefined ) {

        if ( intersects.length > 0 ) {

            if ( INTERSECTED != intersects[ 0 ].object ) {

                if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );

                INTERSECTED = intersects[ 0 ].object;
                INTERSECTED.currentHex = INTERSECTED.material.color.getHex();
                INTERSECTED.material.color.setHex( 0xff0000 );

            }

        } else {

            if ( INTERSECTED ) INTERSECTED.material.color.setHex( INTERSECTED.currentHex );

            INTERSECTED = null;

        }

    }

    if ( INTERSECTED != undefined ) {

        INTERSECTED.dynamic = true;
        INTERSECTED.geometry.__dirtyColors = true;

    }

}

document.getElementById( 'viewport' ).addEventListener( 'mousemove', onMouseMove, false );

我希望将对象的颜色更改为红色,并且它可以随机工作,但是当鼠标悬停时(因此它不会变为以前的颜色)不会工作,或者当鼠标没有移动时,它也会工作,但是不正确与实际物体相交。

1 个答案:

答案 0 :(得分:3)

采用相同的方法,但是您可以在这里找到自己的工作方式:http://jsfiddle.net/mmalex/ed0jhpyk/

在这里使用辅助类:https://github.com/nmalex/three.js-helpers

var cube = new THREE.Mesh(geometry, material);
scene.add(cube);

var mouseMove = new RayysMouseMove(mouse, controls);

//let mouseMove "know" which objects should be interactive
mouseMove.objects.push(cube);

mouseMove.cb.onObjectEnter.push(function(obj) {
    //todo: handle mouse hover, obj here is threejs scene node
});
mouseMove.cb.onObjectLeave.push(function(obj) {
    //todo: handle mouse unhover, obj here is threejs scene node
});

enter image description here