三个js raycaster不适用于css2drenderer

时间:2018-08-18 23:58:47

标签: three.js raycasting

我正在尝试将3D热点添加到3D模型中。为此,我添加了用于3d模型的WebGLRendere和用于热点的CSS2DRenderer。 我正在使用raycaster来检测热点,但未检测到热点。

这是我的代码-

var scene = new THREE.Scene();

var camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.z = 7;

var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);



var platform;
var loader = new THREE.ColladaLoader();
loader.load('model/platform.dae', function(dae){
    platform = dae.scene;
    platform.position.set(0, -3.5, 0.5);
    scene.add(platform);
    scene.add(hotSpot);
});

var hotSpotDiv = document.createElement('div');
hotSpotDiv.className = 'hotSpot';

var hotSpot = new THREE.CSS2DObject(hotSpotDiv);
hotSpot.position.set(-1, 4.2, 0);


var renderer2D = new THREE.CSS2DRenderer();
renderer2D.setSize( window.innerWidth, window.innerHeight );
renderer2D.domElement.style.position = 'absolute';
renderer2D.domElement.style.top = 0;
renderer2D.domElement.style.backgroundColor = 0xff0000;
document.body.appendChild( renderer2D.domElement );


var light = new THREE.AmbientLight( 0x555555 ); // soft white light
scene.add( light );

var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
directionalLight.position.set(-0.5, 0.5, -1);
scene.add( directionalLight );


var mouse = new THREE.Vector2();

document.addEventListener( 'mousemove', onDocumentMouseMove, false );
function onDocumentMouseMove( event ) {
    event.preventDefault();
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
}

var raycaster = new THREE.Raycaster();
var INTERSECTED;


function renderLoop(){
    requestAnimationFrame(renderLoop);
    render();
}
renderLoop();


function render(){
    camera.lookAt( scene.position );
    camera.updateMatrixWorld();
    raycaster.setFromCamera( mouse, camera );
    var intersects = raycaster.intersectObjects( scene.children, true );
    if ( intersects.length > 0 ) {
        if ( INTERSECTED != intersects[ 0 ].object ) {
            console.log(intersects.length + " -- " + intersects[0].object);
            INTERSECTED = intersects[ 0 ].object;
        }
    } else {
        INTERSECTED = null;
    }

    renderer.render(scene, camera);
    renderer2D.render(scene, camera);
    console.log(body);
}


var camControls = new THREE.OrbitControls(camera);
camControls.enableDamping = true;
camControls.dampingFactor =  1;

请让我知道是否还有其他更好的方法可以在3d模型上添加2d可点击按钮。

感谢所有的帮助!

1 个答案:

答案 0 :(得分:0)

仅仅是Andy已经提供的答案的代码版本。

这与Amod的代码有关。

hotSpotDiv.addEventListener('click', function(){ // Do your stuff here });