3gwebtrain
3gwebtrain

Reputation: 15303

How to add simple click event to `cube`

I created a cube using, three.js. but how to add a click event to the cube?

Is it require any additional js libraries or we can directly add the event in to the object?

Here is my code :

$(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);



    });

Upvotes: 0

Views: 1402

Answers (1)

Falk Thiele
Falk Thiele

Reputation: 4494

You cant attach the event directly to your mesh because its not a DOM element.

There is a Three.js extension called threex.domevents which allows you to attach all the mouse events to a mesh, like click, hover, mouse in/ mouse out.

What it does is basically raycasting on your mesh when you trigger a DOM event, pretty straightforward. It works with the latest r71.

Usage:

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

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

Upvotes: 6

Related Questions