Three.js 放置一个通过垂直线的平面

Three.js place a plane through perpendicular by line

我在 3D space 中有一个 线 平面 。我想将平面的宽度和长度线垂直放置。请看我的jsFiddle.

我在 three.js 和矢量计算方面都是新手。

  1. 当前 2. 期望的结果

请指教。 (为我糟糕的英语道歉)

JS代码:

let renderer;
let camera;
let controls;

let scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(54, window.innerWidth / window.innerHeight, 0.1, 1000);

renderer = new THREE.WebGLRenderer({
  antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(new THREE.Color(0xfefefe));
document.body.appendChild(renderer.domElement);

camera.position.set(5, 2, 7.5);


controls = new THREE.OrbitControls(camera, renderer.domElement);


let gridHelper = new THREE.GridHelper(4, 4);
scene.add(gridHelper);

//line is defined by p0-p1
var p0 = new THREE.Vector3(-2, 2, 1);
var p1 = new THREE.Vector3(2, -1, -1);

var material2 = new THREE.LineBasicMaterial({
  color: 0x0000ff
});

//draw the line for visual reference
var geometry = new THREE.Geometry();
geometry.vertices.push(p0, p1);
var line = new THREE.Line(geometry, material2);
scene.add(line);

// Plane
var planeGeom = new THREE.PlaneGeometry(3, 3, 3);
var plane = new THREE.Mesh(planeGeom, new THREE.MeshBasicMaterial({
  color: "pink",
  transparent: true,
  opacity: 0.5,
  side: THREE.DoubleSide
}));

//done!

scene.add(plane);



let animate = function() {
  requestAnimationFrame(animate);
  controls.update();
  renderer.render(scene, camera);
};

animate();

所以你想要这个??

只需将此代码添加到您的 fiddle 之前 scene.add(plane);

plane.position.x = (p1.x + p0.x) / 2;
plane.position.y = (p1.y + p0.y) / 2;
plane.position.z = (p1.z + p0.z) / 2 ;
plane.lookAt(p0);

那么无论您为 p0p1 创建的矢量是什么,平面将始终垂直于它们并位于直线长度的中间。

这是fiddle I have created with the sample

如果此答案解决了您的问题,请将其标记为已接受答案,这样也将帮助有相同问题的其他用户知道它是正确的。