如何使用Three.js鼠标选择

时间:2015-01-12 17:21:38

标签: javascript three.js mouse-picking

我想在此代码中添加对象选择:

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);
    };
}

我怎样才能以最简单的方式做到这一点?

P.S。 只有加载了“loadCastle”方法的城堡网格,我希望能够选择它们。

编辑:

我尝试了这样的AlmazVildanov:

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)
}

但是当我点击模型时没有任何反应,控制台中没有任何消息。

编辑2: 对象选择工作正常。解决。

1 个答案:

答案 0 :(得分:0)

我的问题的解决方案是使用@AlmazVildanov EventsControls