我有一个网格,我想通过用户输入来控制它的偏航和俯仰。我天真地尝试围绕 z 和 y 轴旋转网格,这似乎可以控制偏航,但上下是不稳定的。
function checkKeys(keys) {
if (keys.left) spaceship.rotation.z += .05;
if (keys.right) spaceship.rotation.z -= .05;
if (keys.up) spaceship.rotation.y += .05;
if (keys.down) spaceship.rotation.y -= .05;
}
如何使左/右控制飞机的偏航和上/下控制俯仰?
http://jsfiddle.net/trevordixon/d9BN9/2/
更新:我简化了 wagerfield 提到的 FlyControls.js,因此它服从我的游戏手柄并仅处理旋转。这是我最终得到的结果(https://gist.github.com/trevordixon/5783321):
THREE.FlyControls = function(object) {
this.object = object;
// API
this.movementSpeed = 1.0;
this.rollSpeed = 0.005;
// disable default target object behavior
this.object.useQuaternion = true;
// internals
this.tmpQuaternion = new THREE.Quaternion();
this.moveState = {up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0};
this.moveVector = new THREE.Vector3(0, 0, 0);
this.rotationVector = new THREE.Vector3(0, 0, 0);
this.handleEvent = function(event) {
if (typeof this[event.type] == 'function') {
this[event.type](event);
}
};
this.update = function(delta) {
this.moveState.yawLeft = -gamepad.axes[2];
this.moveState.pitchDown = gamepad.axes[3];
this.moveState.rollLeft = (Math.abs(gamepad.axes[0]) < 0.15 ? 0 : gamepad.axes[0]) ||
gamepad.buttons[15]/2;
this.moveState.rollRight = (Math.abs(gamepad.axes[1]) < 0.15 ? 0 : gamepad.axes[1]) ||
gamepad.buttons[14]/2;
this.updateRotationVector();
var moveMult = delta * this.movementSpeed;
var rotMult = delta * this.rollSpeed;
this.object.translateX(this.moveVector.x * moveMult);
this.object.translateY(this.moveVector.y * moveMult);
this.object.translateZ(this.moveVector.z * moveMult);
this.tmpQuaternion.set(this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1).normalize();
this.object.quaternion.multiply(this.tmpQuaternion);
// expose the rotation vector for convenience
this.object.rotation.setEulerFromQuaternion(this.object.quaternion, this.object.eulerOrder);
};
this.updateRotationVector = function() {
this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
};
function bind(scope, fn) {
return function () {
fn.apply( scope, arguments );
};
};
this.updateRotationVector();
};