我有这个带有基本坐标的 json,我需要用它在 Threeejs 中渲染一个立方体。高度是给定的常数(在本例中假设为 1)。
{
"points": [
{
"x": 0,
"y": 0,
"z": 0
},
{
"x": 0,
"y": -1,
"z": 0
},
{
"x": 1,
"y": 0,
"z": 0
},
{
"x": 1,
"y": -1,
"z": 0
}
]
}
我应该在 Three.js 中使用什么几何图形?
我尝试过使用 ExtrudeGeometry,但渲染的立方体渲染不正确(缺少顶部)并且基础坐标错误。
使用此代码尝试一下:
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
let renderer, scene, camera;
const data = {
"points": [
{
"x": 0,
"y": 0,
"z": 0
},
{
"x": 0,
"y": -1,
"z": 0
},
{
"x": 1,
"y": -1,
"z": 0
},
{
"x": 1,
"y": 0,
"z": 0
},
]
};
init();
animate();
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 0.1, 100 );
camera.position.set( 5, 2, 5 );
const shape = new THREE.Shape();
shape.moveTo( 0, 0 ); // first point
for ( let i = 1, l = data.points.length; i < l; i ++ ) {
const point = data.points[ i ];
shape.lineTo( point.x, point.y );
}
const geometry = new THREE.ExtrudeGeometry( shape, { depth: 1, bevelEnabled: false } );
geometry.center(); // optional
const material = new THREE.MeshNormalMaterial();
// mesh
const mesh = new THREE.Mesh( geometry, material );
scene.add( mesh );
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setPixelRatio( window.devicePixelRatio );
document.body.appendChild( renderer.domElement );
const controls = new OrbitControls( camera, renderer.domElement );
}
function animate() {
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
您必须注意以 CCW 顺序定义底座的轮廓。