三个 JS - 为什么线长等于零?

Three JS - why is line length equal to zero?

初学三个js。探索使用线段。我正在尝试确定一条线的长度。我正在使用 computeLineDistances();获取线长的方法。该线沿 x 轴绘制,终止于 x=10。由于某种原因,日志控制台 returns 为零值。有没有人解释为什么控制台中返回的长度 = 0;

var myLength =0 ;

//a line start point (0,0,0), end point (10,0,0)
var points = []; // x, y, z
points.push( new THREE.Vector3( 0,  0, 0 ) ); // start point
points.push( new THREE.Vector3( 10, 0, 0 ) ); 

var geometry = new THREE.BufferGeometry().setFromPoints( points );

var axesHelper = new THREE.AxesHelper( 5 );
scene.add( axesHelper );

drawLine(); //call the line drawing function

// function to draw a line
function drawLine () {
    
var line = new THREE.Line( geometry, material );

scene.add( line );
//var myLength = line.distanceTo();
var myLength = line.computeLineDistances();

//return (line);

} // end function drawLine

//log
console.log("myLength: ", myLength);

下面是fiddle link:

https://jsfiddle.net/kdwoell/kgm6j1q4/

您将 var myLength 初始化为 0 作为函数外部的常量。到目前为止,当您定义内部 var myLength 时,您将在所有嵌套调用中局部覆盖 myLength。

您只需尝试将 var myLength = line.computeLineDistances(); 替换为 myLength = line.computeLineDistances();

如果您想知道行的总长度,那么,在非索引缓冲区几何体上调用 .computeLineDistances() 后,您可以从以下位置获取它:

line.geometry.attributes.lineDistance.array[ length_of_points_array - 1]

line.geometry.attributes.lineDistance.getX(line.geometry.attributes.lineDistance.count - 1);

很快:

var ld = line.geometry.getAttribute("lineDistance");
console.log(ld.getX(ld.count - 1));

示例:

body {
  overflow: hidden;
  margin: 0;
}
<script type="module">
import * as THREE from "https://threejs.org/build/three.module.js";
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 100);
camera.position.set(0, 0, 20);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

var pts = [
  new THREE.Vector3(0, 0, 0),
  new THREE.Vector3(10, 0, 0),
  new THREE.Vector3(10, 10, 0)
];
var geom = new THREE.BufferGeometry().setFromPoints(pts);
var mat = new THREE.LineBasicMaterial({color: "yellow"});
var line = new THREE.Line(geom, mat);
line.computeLineDistances();

var ld = line.geometry.getAttribute("lineDistance");
console.log("line's total length: " + ld.getX(ld.count - 1));

scene.add(line);

renderer.setAnimationLoop(()=>{
  renderer.render(scene, camera);
});
</script>