沿移动方向旋转对象

时间:2019-01-03 20:23:26

标签: javascript three.js

例如,我按下按钮“ W”,对象应转向侧移

enter image description here

if (keyBoard[87]) {
    camera.position.x -= Math.PI / 10;
    bulba.position.x -= Math.PI / 10;
}

if (keyBoard[83]) {
    camera.position.x += Math.PI / 10;
    bulba.position.x += Math.PI / 10;
}

if (keyBoard[65]) {
    camera.position.z += Math.PI / 10;
    bulba.position.z += Math.PI / 10;
}

if (keyBoard[68]) {
    camera.position.z -= Math.PI / 10;
    bulba.position.z -= Math.PI / 10;
}

我对move的简单实现

1 个答案:

答案 0 :(得分:1)

使用Tween.js一个非常粗糙的概念:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 10, 5);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var boxGeom = new THREE.BoxBufferGeometry(1, 1, 3);
boxGeom.translate(0, 0, 2.5);
var box = new THREE.Mesh(boxGeom, new THREE.MeshNormalMaterial());
box.rotation.y = Math.PI * 0.5;
scene.add(box);

window.addEventListener("keydown", onKeyDown, false);

function onKeyDown(event) {

  if (![65, 68, 83, 87].includes(event.keyCode)) return;

  var angleTo = 0;
  switch (event.keyCode) {
    case 87:
      angleTo = Math.PI;
      break;
    case 65:
      angleTo = Math.PI * -0.5;
      break;
    case 83:
      angleTo = 0;
      break;
    case 68:
      angleTo = Math.PI * 0.5;
      break;
  }

  startTween(angleTo);

}

function startTween(angleTo) {
  let tween = new TWEEN.Tween(box.rotation).to({
    y: angleTo
  }, 250).onStart(() => {
    window.removeEventListener("keydown", onKeyDown, false);
  }).onComplete(() => {
    window.addEventListener("keydown", onKeyDown, false)
  });
  tween.start();
}

renderer.setAnimationLoop(() => {
  TWEEN.update();
  renderer.render(scene, camera);
})
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/100/three.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/17.2.0/Tween.min.js"></script>