使用three.js自定义形状

时间:2019-10-23 05:11:54

标签: javascript three.js 3d geometry-surface

我正在尝试在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

1 个答案:

答案 0 :(得分:2)

在您的情况下,使用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