我正在尝试在3D空间中相对于视口的2D x / y移动THREE.Object3D
。在moveChar()
中,使用THREE.Quaternion
进行了一些计算,并且可以成功地在正确的平面上移动整个game
(THREE.Group),但是我正在尝试移动{{1} }。
我尝试在每个cha
之间交换变量,将quat和inverse quat应用于不同的事物,以及大量其他事物。我的数学不如我想的那么先进,所以请多包涵。
main.js
THREE.Object3D
当我按WASD时,let container;
let camera;
let controls;
let game;
let renderer;
let scene;
function init() {
container = document.querySelector('#scene-container');
scene = new THREE.Scene();
const fov = 35;
const aspect = container.clientWidth / container.clientHeight;
const near = 0.1;
const far = 100;
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
game = new THREE.Group();
scene.add(game);
controls = new THREE.ObjectControls(camera, container, game);
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial();
var mesh1 = new THREE.Mesh(geometry, material);
game.add(mesh1);
//cha stands for character
var cha = new THREE.Mesh(geometry, material);
cha.position.set(0,1,0);
game.add(cha);
renderer = new THREE.WebGLRenderer();
renderer.setSize(container.clientWidth, container.clientHeight);
renderer.setPixelRatio(window.devicePixelRatio);
container.appendChild(renderer.domElement);
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
}
function moveChar(ev) {
var keyCode = event.keyCode;
var offset = new THREE.Vector3();
// so camera.up is the orbit axis
var quat = new THREE.Quaternion().setFromUnitVectors(game.up, new THREE.Vector3(0, 1, 0));
var quatInverse = quat.clone().inverse();
var position = game.position;
offset.copy(position);
// rotate offset to "y-axis-is-up" space
offset.applyQuaternion(quat);
switch (keyCode) {
case 68: //d
offset.x += 1;
break;
case 83: //s
offset.y -= 1;
break;
case 65: //a
offset.x -= 1;
break;
case 87: //w
offset.y += 1;
break;
}
// rotate offset back to "camera-up-vector-is-up" space
offset.applyQuaternion(quatInverse);
//****** Here is where the group is being transformed ******
position.add(offset.sub(position));
// cha.position.add(offset.sub(position));
}
document.addEventListener("keydown", moveChar);
init();
应该相对于视口的2D x / y移动。我可以成功移动它,但是翻译最终不正确,并且它在3D空间中无法预测地移动。