Three.js place a plane through perpendicular by line

纵饮孤独 提交于 2021-02-10 20:50:58

问题


I have an a line and plane in 3D space. I want to place plane's width and length line as perpendicular by line. Please see my jsFiddle.

I am newbie at both three.js and vector calculation.

  1. Current 2. Desired result

Please advice me. (Apologies for my bad English)

JS code:

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();

回答1:


So you want this??

just add this code to your fiddle before 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);

Then whatever the vectors you create for p0 and p1, the plane will always be perpendicular to them and positioned in the middle of the line length.

Here's the fiddle I have created with the sample

If this answer solves your question, please mark it as answer accepted, in that way will also help other users with the same question to know it was right.



来源:https://stackoverflow.com/questions/65020488/three-js-place-a-plane-through-perpendicular-by-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!