three.js 的自定义形状

Custom shapes with three.js

我正在尝试在 three.js 中创建一个多边形 这是我使用的代码。

function DeployZone(coordinatesList) {
// Create the polygon Shape
{


    var material = new THREE.MeshLambertMaterial({ color: 0x00ffcc });

    var faces = [0, 1, 2, 3, 4];

    var geometry = new THREE.Geometry();
    for (var i = 0; i < coordinatesList.length; i++) {
        geometry.vertices.push(new THREE.Vector3(
            coordinatesList[i].x,
            coordinatesList[i].z,
            coordinatesList[i].y
        ));
    }


    for (var i = 0; i<faces.length; i++) {
        for (var j = 1; j < faces.length - 1; j++) {
            geometry.faces.push(new THREE.Face3(faces[0], faces[j], faces[j + 1]));
        }
    }

    geometry.computeFaceNormals();
    var zone = new THREE.Mesh(geometry, material);
    scene.add(zone);

}
}

这是我传递的坐标:

var coordinatesList = new List<Coordinates>() {
      new Coordinates(X:0,Y:0,Z:0),
       new Coordinates(X:0,Y:10,Z:0),
       new Coordinates(X:5,Y:10,Z:0),
       new Coordinates(X:2,Y:8,Z:0),
       new Coordinates(X:5,Y:5,Z:0)
    };

虽然它确实创建了一个多边形,但它没有创建所需的多边形。 (x:2,y:8,z:0) 处的顶点不在适当位置。问题是没有正确定义三角形面。请对此提供帮助,以便面和顶点可以是动态的并且生成的几何体是合适的。

非常感谢。

P.S。我尝试使用形状,但这似乎也不适合我。我在代码中使用了this

在您的情况下使用 THREE.Shape() 完全没问题:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 100);
camera.position.set(0, 5, 10);
camera.lookAt(0, 5, 0);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

var grid = new THREE.GridHelper(30, 30, 0xffffff, 0x404040);
grid.rotation.x = Math.PI * 0.5;
scene.add(grid);

var coordinatesList = [
  new THREE.Vector3(0, 0, 0),
  new THREE.Vector3(0, 10, 0),
  new THREE.Vector3(5, 10, 0),
  new THREE.Vector3(2, 8, 0),
  new THREE.Vector3(5, 5, 0)
];


// shape
var geomShape = new THREE.ShapeBufferGeometry(new THREE.Shape(coordinatesList));
var matShape = new THREE.MeshBasicMaterial({color:"blue"});
var shape = new THREE.Mesh(geomShape, matShape);
scene.add(shape);

// points
var geom = new THREE.BufferGeometry().setFromPoints(coordinatesList);
var matPoints = new THREE.PointsMaterial({size: 0.55, color: "pink"});
var points = new THREE.Points(geom, matPoints);
scene.add(points);


// lines
var matLines = new THREE.LineBasicMaterial({color: "magenta"});
var lines = new THREE.LineLoop(geom, matLines);
scene.add(lines);


renderer.setAnimationLoop(() => {
  renderer.render(scene, camera);
});
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/three.min.js"></script>

Three.js r109