用Three.js绘制一个基本三角形

时间:2016-09-08 19:09:45

标签: javascript three.js

我很想学习三个。我想要一个基本的三角形,但我的代码不起作用。

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 70, window.innerWidth/window.innerHeight, 0.1, 1000 );
camera.position.z = 10;


var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var geometry = new THREE.Geometry();
geometry.vertices= [new THREE.Vector3(2,1,0), new THREE.Vector3(1,3,0), new THREE.Vector3(3,4,0)]; 
geometry.faces = [new THREE.Face3(0,1,2)];
var mesh= new THREE.Mesh( geometry, new THREE.MeshBasicMaterial({ color: 0xffff00 }) );
scene.add(mesh);


renderer.render(scene, camera);

我做错了什么?

2 个答案:

答案 0 :(得分:0)

您必须小心将顶点添加到面部的顺序。如果顺序遵循顺时针顺序,表面的法向矢量将指向下方,并且由于您的相机从上方看,您将看不到三角形。如果订单是逆时针方向,则法线将指向您的相机。

您可以将geometry.faces = [new THREE.Face3(0,1,2)];更改为geometry.faces = [new THREE.Face3(1,0,2)];,这样就可以了。

其他选项是使用side: THREE.DoubleSide指定素材,以便将其应用于脸部的两侧:new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.DoubleSide }

Here是一个有效的代码。

答案 1 :(得分:0)

带面孔

var geom = new THREE.Geometry();
var v1 = new THREE.Vector3(0, 0, 0);
var v2 = new THREE.Vector3(30, 0, 0);
var v3 = new THREE.Vector3(30, 30, 0);
var triangle = new THREE.Triangle(v1, v2, v3);
var normal = triangle.normal();
geom.vertices.push(triangle.a);
geom.vertices.push(triangle.b);
geom.vertices.push(triangle.c);
geom.faces.push(new THREE.Face3(0, 1, 2, normal));
var mesh = new THREE.Mesh(geom, new THREE.MeshNormalMaterial());
scene.add(mesh);

仅大纲

 var geometry = new THREE.Geometry();
geometry.vertices.push(new THREE.Vector3(-30, 2, 2));
geometry.vertices.push(new THREE.Vector3(2, 30, 2));
geometry.vertices.push(new THREE.Vector3(30, 2, 2));
geometry.vertices.push(new THREE.Vector3(-30, 2, 2));

var line = new THREE.Line(
  geometry,
  new THREE.LineBasicMaterial({ color: 0x00ff00 })
);
scene.add(line);

enter image description here