【问题标题】:How to rotate an object to match a normal vector in three.js?如何旋转对象以匹配three.js中的法线向量?
【发布时间】:2022-01-21 07:11:06
【问题描述】:

我有一个对象,比如说一辆车,它的 z 轴旋转已经设置好了,所以它朝向它前进的方向。

汽车也位于由归一化法线向量(nx, ny, nz) 表示的斜坡(平面)上。我现在如何旋转汽车的 x 和 y 轴以使其与斜坡对齐?也就是说汽车自身的法向量匹配(nx, ny, nz)

【问题讨论】:

  • 你可以把你的车放在另一个物体上,然后用这个物体在斜坡上对齐

标签: javascript vector three.js


【解决方案1】:

只需将您的汽车网格嵌套在地面网格中,这样地面的旋转就会从父节点继承到子节点。通过这种方式,您可以将父级的旋转设置为地面坡度,您只需担心将汽车绕其本地 y 轴转动,而无需任何额外计算。

这是一个简单的演示:

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight,  1, 200);
camera.position.z = 75;

const renderer = new THREE.WebGLRenderer({
    antialias: true,
    canvas: document.querySelector("#canvas")
});
renderer.setSize(window.innerWidth, window.innerHeight);
const controls = new THREE.OrbitControls( camera, renderer.domElement );

// World axes
const axesHelper = new THREE.AxesHelper( 30 );
scene.add( axesHelper );

// Create green ground plane
const planeGeom = new THREE.PlaneGeometry(60, 60, 20, 20);
planeGeom.rotateX(Math.PI / 2);
const slope = new THREE.Mesh(
  planeGeom,
  new THREE.MeshBasicMaterial({ color: 0x99ff00, side: THREE.DoubleSide, wireframe: true })
);
scene.add(slope);

// Add purple car
const geometry = new THREE.BoxGeometry( 10, 5, 20);
const material = new THREE.MeshNormalMaterial( { wireframe: false } );
const car = new THREE.Mesh( geometry, material );
car.position.y = 2.5;
slope.add( car );

// Add car axes
const carAxes = new THREE.AxesHelper( 20 );
car.add( carAxes );

function animate(time) {
  // Spin car around its own y-axis
  car.rotation.y += 0.005;
  
  // Swing ground plane back and forth
  slope.rotation.z = Math.sin(time * 0.001) * 0.5;

renderer.render(scene, camera);
  requestAnimationFrame(animate);
}

animate(0);
html, body { margin:0; padding:0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script><script src="https://rawgit.com/mrdoob/three.js/dev/examples/js/controls/OrbitControls.js"></script>

<canvas id="canvas"></canvas>

或者如果你想将它嵌套在一个空对象中,你可以将它放在inside a Group

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-28
    • 2014-10-24
    • 1970-01-01
    • 2012-02-20
    • 2015-02-06
    • 2019-11-25
    • 2015-12-27
    • 2021-12-18
    相关资源
    最近更新 更多