How to manage click events on the three.js scene?

advertisements

I have a world map layer as a plane geometry, now i want to handle click events on different parts (For example continents or country). How to handle popup events on particular part like (popup of information or video playing or image data with links etc.)

Here's a fiddle that already has the scene setup.

var camera, scene, renderer;
var geometry, material, mesh;

window.addEventListener("click", onClick, false);

function onClick() {
    alert("Replace me with code to add an object!");
}

var init = function () {

    renderer = new THREE.CanvasRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
    camera.position.z = 500;

    scene = new THREE.Scene();

geometry = new THREE.CubeGeometry(200, 200, 200);
material = new THREE.MeshBasicMaterial({
                color: 0x000000,
                wireframe: true,
                wireframeLinewidth: 2
            });

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

}

var animate = function () {

    requestAnimationFrame(animate);

    mesh.rotation.x = Date.now() * 0.0005;
    mesh.rotation.y = Date.now() * 0.001;

    renderer.render(scene, camera);

}

init();
animate();

the click event is applied to whole scene, i have created multiple cubes in that example and when clicked on that it is showing the same click event for all parts.


What you ask is too complex, you need to break it down. First problem you want to solve is to find out which object is being clicked.

You can do raycasting or gpu picking. since you sound like a beginner I would suggest you to start with raycasting. Here is the tutorial