マウスによる移動、回転、拡縮操作
「three.js」の3Dオブジェクトには、「位置(position)」「回転(rotation)」「拡縮倍率(scale)」の値があります。このオブジェクトにはそれぞれ「x, y, z」の値があり、この値を書き換えることで、移動や回転や拡縮を行えます。
注意しなければならない点は、これらの値を変えるごとに、必ずレンダリングを行う必要があることです。値を変更しても、レンダリングを行わなければ表示は反映されません。
以下、ラジオボタンで「移動」「回転」「拡縮」を切り替えるUIを追加して、マウスで立方体を操作する「crocro.bc.useMouse.js」を掲載します。立方体の作成は、前回作成した「crocro.bc.mkColCube」関数をそのまま利用しました。
//= サンプル:マウスによる移動、回転、拡縮操作
//== マウスによる移動、回転、拡縮操作
crocro.bc.useMouse = function() {
// 変数の初期化
var d3 = crocro.bc.d3; // 3D格納用
// 要素の作成と格納
var cube = crocro.bc.mkColCube();
cube.rotation.x = Math.PI / 4;
cube.rotation.y = Math.PI / 4;
cube.rotation.z = Math.PI / 4 * 4;
d3.scene.add(cube);
crocro.bc.render();
// UIの作成
crocro.bc.useMouse_mkUI();
// マウス操作の作成
d3.tgt = cube; // 操作対象を設定
crocro.bc.useMouse_setMouse();
// 終了処理
crocro.bc.setFinalize(function() {
crocro.bc.d3.tgt = null; // 操作対象を解除
})
};
//== UIの作成
crocro.bc.useMouse_mkUI = function() {
// UIの作成
crocro.bc.ui
.append(
$('<input type="radio">')
.attr("name", "uiCntrlTyp")
.attr("id", "uiCntrlTyp_mv")
.attr("value", "mv")
.attr("checked", true)
).append(
$('<label>')
.attr("for", "uiCntrlTyp_mv")
.text("移動")
).append(
$('<input type="radio">')
.attr("name", "uiCntrlTyp")
.attr("id", "uiCntrlTyp_rtt")
.attr("value", "rtt")
).append(
$('<label>')
.attr("for", "uiCntrlTyp_rtt")
.text("回転")
).append(
$('<input type="radio">')
.attr("name", "uiCntrlTyp")
.attr("id", "uiCntrlTyp_scl")
.attr("value", "scl")
).append(
$('<label>')
.attr("for", "uiCntrlTyp_scl")
.text("拡縮")
);
};
//== マウス操作の作成
crocro.bc.useMouse_setMouse = function() {
// 変数の初期化
var d3 = crocro.bc.d3; // 3D格納用
var cntnr = crocro.bc.cntnr; // コンテナー
var isAct = false;
var posX, posY;
var actType;
//=== マウス操作 開始
var msStrt = function(event) {
isAct = true; // 動作状態に移行
// 位置の取得
posX = event.pageX;
posY = event.pageY;
// ラジオボタンで動作種類を切り替え
actType = $('input[name="uiCntrlTyp"]:checked').val();
};
//=== マウス操作 移動
var msMv = function(event) {
// 動作状態でなければ終了
if (! isAct) {return;}
// 位置の取得
var newX = event.pageX;
var newY = event.pageY;
// 移動、回転、拡縮操作
if (actType == "mv") {
// 移動
crocro.bc.changePos(d3.tgt, newX - posX, newY - posY);
} else
if (actType == "rtt") {
// 回転
crocro.bc.changeRtt(d3.tgt, newX - posX, newY - posY);
} else
if (actType == "scl") {
// 拡縮
crocro.bc.changeScl(d3.tgt, newX - posX, newY - posY);
}
// 位置の更新
posX = newX;
posY = newY;
// レンダリング
crocro.bc.render();
};
//=== マウス操作 終了
var msEnd = function() {
isAct = false; // 動作状態を解除
};
// マウス操作の登録
cntnr.mousedown(msStrt);
cntnr.mousemove(msMv);
cntnr.mouseup(msEnd);
$(window).blur(msEnd);
}
//== 位置の変更
crocro.bc.changePos = function(tgt, difX, difY) {
// 移動
tgt.position.x += difX;
tgt.position.y -= difY;
}
//== 回転の変更
crocro.bc.changeRtt = function(tgt, difX, difY) {
// 回転
tgt.rotation.y += difX / 100;
tgt.rotation.x += difY / 100;
}
//== 拡縮の変更
crocro.bc.changeScl = function(tgt, difX, difY) {
// 回転
var scl = (difX + difY) / 100;
tgt.scale.x += scl;
tgt.scale.y += scl;
tgt.scale.z += scl;
}
