简体   繁体   English

如何旋转 object 以匹配 three.js 中的法线向量?

[英]How to rotate an object to match a normal vector in three.js?

I have an object, lets say a car, and it's z-rotation is already set so its facing the direction its heading towards.我有一辆 object,可以说是一辆车,它的 z 轴旋转已经设置好,所以它朝向它的前进方向。

The car is also on a ground which is on a slope (plane) that is represented by the normalized normal vector (nx, ny, nz) .汽车也在由归一化法线向量(nx, ny, nz)表示的斜坡(平面)上的地面上。 How can I now rotate the car's x and y axis so that it aligns with the slope?我现在如何旋转汽车的 x 和 y 轴以使其与斜坡对齐? Which is to say the car's own normal vector matches (nx, ny, nz) ?也就是说汽车自身的法线向量匹配(nx, ny, nz)

Just nest your car Mesh inside the ground Mesh, so the ground's rotations get inherited from parent to child.只需将您的汽车网格嵌套在地面网格内,这样地面的旋转就会从父级继承到子级。 This way you can set the parent's rotation as the ground slope, and all you have to worry is turning the car around its local y-axis without any extra calculations.通过这种方式,您可以将父级的旋转设置为地面坡度,您只需担心将汽车绕其本地 y 轴转动,而无需任何额外的计算。

Here's a simple demo:这是一个简单的演示:

 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>

Or if you want to nest it inside an empty object, you can place it inside a Group .或者,如果你想将它嵌套在一个空的 object 中,你可以将它放在一个Group中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM