如何将简单点击事件添加到`cube`

时间:2015-07-14 10:12:06

标签: jquery three.js

我使用cube创建了three.js。但是如何将click事件添加到cube

是否需要任何其他js库,或者我们可以直接将事件添加到对象中?

这是我的代码:

$(function () {


        var scene           = new THREE.Scene();
        var camera          = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.1, 1000);
        var webGLRenderer   = new THREE.WebGLRenderer({ antialias : true });

        webGLRenderer.setClearColor (0xEEEEEE, 1.0);
        webGLRenderer.setSize ( window.innerWidth, window.innerHeight );
        webGLRenderer.shadowMapEnabled = true;

        var cube = createMesh(new THREE.CubeGeometry(5, 5, 5), "floor-wood.jpg" );
        cube.position.x = -12;
        scene.add(cube);
        // console.log(cube.geometry.faceVertexUvs);

        var step = 0;

        render ();

        camera.position.x = 00;
        camera.position.y = 12;
        camera.position.z = 28;
        camera.lookAt(new THREE.Vector3(0, 0, 0));

        var ambiLight = new THREE.AmbientLight(0x141414)
        scene.add(ambiLight);

        var light = new THREE.DirectionalLight();
        light.position.set(20, 30, 20);
        scene.add(light);

        function createMesh (geo, imgFile) {

            var texture = THREE.ImageUtils.loadTexture ("images/" + imgFile);
            var mat      = new THREE.MeshPhongMaterial();
            mat.map = texture;

            var mesh = new THREE.Mesh ( geo, mat);

            return mesh;

        }

        function render () {

            cube.rotation.y = step;
            cube.rotation.x = step;

            requestAnimationFrame ( render );
            webGLRenderer.render( scene, camera );
        }


        $('#webGL-output')
            .append(webGLRenderer.domElement);



    });

1 个答案:

答案 0 :(得分:6)

您无法将事件直接附加到网格,因为它不是DOM元素。

有一个名为threex.domevents的Three.js扩展名,允许您将所有鼠标事件附加到网格中,例如点击,悬停,鼠标悬停/鼠标移出。

当你触发DOM事件时,它的作用基本上是在你的网格上进行光线投射,非常简单。它适用于最新的r71。

用法:

var domEvents   = new THREEx.DomEvents(camera, renderer.domElement)

domEvents.addEventListener(mesh, 'click', function(event){
    console.log('you clicked on mesh', mesh)
}, false)