javascriptthree.jsmouse-picking

How to use Three.js mouse picking


I would like to add object picking to this code:

var Three = new function () {
    this.scene = new THREE.Scene()

    this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 1000)
    this.camera.position.set(20, 52, 20);
    this.camera.rotation.order = 'YXZ';
    this.camera.rotation.y = -Math.PI / 4;
    this.camera.rotation.x = Math.atan(-1 / Math.sqrt(2));
    this.camera.scale.addScalar(1);

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

    var ground = new THREE.Mesh(new THREE.PlaneBufferGeometry(436, 624), new THREE.MeshBasicMaterial({map: THREE.ImageUtils.loadTexture('/img/maps/1.png')}));
    ground.rotation.x = -Math.PI / 2; //-90 degrees around the x axis
    this.scene.add(ground);

    var light = new THREE.PointLight(0xFFFFDD);
    light.position.set(-1000, 1000, 1000);
    this.scene.add(light);

    var loader = new THREE.JSONLoader();
    this.loadCastle = function (color, x, y) {
        loader.load('/models/castle.json', getGeomHandler(color, x * 4 - 214, y * 4 - 309, 0.5));
    }
    this.init = function () {
        $('#game').append(Three.renderer.domElement);
        Three.render();
    }
    this.render = function () {
        requestAnimationFrame(Three.render);
        Three.renderer.render(Three.scene, Three.camera);
    };
}

How can I do this in the simplest way?

p.s. There are only castles meshes loaded with "loadCastle" method and I want to be able to pick them.

Edit:

I tried AlmazVildanov sugestion like this:

function getGeomHandler(color, x, y, scale) {
    return function (geometry) {
        var model = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({color: color}));
        model.scale.set(scale, scale, scale);
        model.position.set(x, 0, y);
        model.name = color + '_' + x + '_' + y;
        Three.scene.add(model);
        EventsControls.attach(model);
    };
}

EventsControls = new EventsControls(Three.camera, Three.renderer.domElement);
EventsControls.displacing = false;
EventsControls.onclick = function () {
    console.log('aaa')
    console.log(this.focused.name)
}

but when I'm clicking on models nothing happens, no messages in console.

EDIT 2: Object picking is working fine. Solved.


Solution

  • Solution to my question is to use @AlmazVildanov EventsControls