我想用Three.js生成2D八边形

时间:2018-01-20 18:15:34

标签: javascript three.js coordinates

当我尝试生成一个正八边形时,我得到了一个特殊的三角形代码:

    var geom = new THREE.Geometry(); 

    geom.vertices.push( new THREE.Vector3(100, 250, 0));
    geom.vertices.push( new THREE.Vector3(250, 100, 0));
    geom.vertices.push( new THREE.Vector3(250, -100, 0));
    geom.vertices.push( new THREE.Vector3(100, -250, 0));
    geom.vertices.push( new THREE.Vector3(-100, 250, 0));
    geom.vertices.push( new THREE.Vector3(-250, -100, 0));
    geom.vertices.push( new THREE.Vector3(-250, 100, 0));
    geom.vertices.push( new THREE.Vector3(-100, 250, 0));

    geom.faces.push( new THREE.Face3(0, 1, 2));
    geom.faces.push( new THREE.Face3(0, 2, 3));
    geom.faces.push( new THREE.Face3(0, 3, 4));
    geom.faces.push( new THREE.Face3(0, 4, 5));
    geom.faces.push( new THREE.Face3(0, 5, 6));
    geom.faces.push( new THREE.Face3(0, 6, 7));



    var material = new THREE.MeshBasicMaterial();

    var mesh = new THREE.Mesh( geom, material);

    mesh.position.set(0, 0, -1000);

    scene.add(mesh);

此外,生成的三角形的一个顶点位于我在代码中甚至没有提到的地方。 可能只显示最后添加的面,但我希望看到彼此相邻的所有面形成一个正八边形。

1 个答案:

答案 0 :(得分:1)

因此,面中顶点的顺序是逆时针的,第5和第8点是不同的:



var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(0, 0, 500);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);

var geom = new THREE.Geometry();

geom.vertices.push(new THREE.Vector3(100, 250, 0));
geom.vertices.push(new THREE.Vector3(250, 100, 0));
geom.vertices.push(new THREE.Vector3(250, -100, 0));
geom.vertices.push(new THREE.Vector3(100, -250, 0));
geom.vertices.push(new THREE.Vector3(-100, -250, 0)); //  y-coordinate is corrected
geom.vertices.push(new THREE.Vector3(-250, -100, 0));
geom.vertices.push(new THREE.Vector3(-250, 100, 0));
geom.vertices.push(new THREE.Vector3(-100, 250, 0));

geom.faces.push(new THREE.Face3(0, 2, 1)); // order of vertices
geom.faces.push(new THREE.Face3(0, 3, 2));
geom.faces.push(new THREE.Face3(0, 4, 3));
geom.faces.push(new THREE.Face3(0, 5, 4));
geom.faces.push(new THREE.Face3(0, 6, 5));
geom.faces.push(new THREE.Face3(0, 7, 6));

geom.computeFaceNormals();
geom.computeVertexNormals();

var material = new THREE.MeshBasicMaterial({
  color: "white"
});

var mesh = new THREE.Mesh(geom, material);

scene.add(mesh);

var points = new THREE.Points(geom, new THREE.PointsMaterial({
  size: 20,
  color: 0xff0000
}));
scene.add(points); // just to visualize the points

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

body {
  overflow: hidden;
  margin: 0;
}

<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>
&#13;
&#13;
&#13;