LoginSignup
7
7

More than 5 years have passed since last update.

raycasterでクリックイベントの実現

Posted at

デモ:http://mo49.tokyo/threejs/raycaster2.html

つくったmeshをrayReceiveObjectsに集める。

javascript
var rayReceiveObjects = []; // 光線を受けるオブジェクト配列

for (var i = 0; i < 20; i++) {
    rayReceiveObjects.push( meshs[i] );
}

光線と交わるオブジェクトとしてrayReceiveObjectsを登録し、
mousedownイベントの中でraycasterを実行。

javascript
var raycaster = new THREE.Raycaster(); 
var mouse = new THREE.Vector2();

window.addEventListener( 'mousedown', onDocumentMouseDown, false );
function onDocumentMouseDown( event ) {

    // イベントの伝播の無効化
    event.preventDefault();

    // マウスポインタの位置座標の取得
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1; 
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1; 

    // 光線を発射
    raycaster.setFromCamera( mouse, camera );
    // 光線と交わるオブジェクトを収集
    var intersects = raycaster.intersectObjects( rayReceiveObjects );

    // 連想配列をとりだす
    var bookAry = {
        '火花' : 'http://www.amazon.co.jp/dp/4163902309',
        '' : 'http://www.amazon.co.jp/dp/4062194856',
        '朝が来る' : 'http://www.amazon.co.jp/dp/4163902732',
        '王とサーカス' : 'http://www.amazon.co.jp/dp/4488027512',
        '君の膵臓をたべたい' : 'http://www.amazon.co.jp/dp/4575239054'
    };

    // 交わるオブジェクトが1個以上の場合
    if ( intersects.length > 0 ) {
        // 最も近いオブジェクトの名前をアラート表示する
        alert(intersects[0].object.name + "をご購入ですね?");
        console.log("カメラ位置座標からの距離:" + intersects[0].distance);
        console.log("光線との交差座標(" + intersects[0].point.x + ", " + intersects[0].point.y + ", " + intersects[0].point.z + ")" );
        console.log(intersects[0]);

        for(var i in bookAry){
            if (intersects[0].object.name == i) {
                window.location.href = bookAry[i];
            }
        }
    }
}

参考
three.jsによるHTML5 3Dグラフィックス〈上〉―ブラウザで実現するOpenGL(WebGL)の世界

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7