自学内容网 自学内容网

从Unity到Three.js(动态创建mesh)

js var let const基础

手动创建模型mesh功能测试,此功能跑通就可以实现很多功能了,如点云转mesh,磨碎效果等等。

import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);

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

//只使用顶点数据创建mesh
//创建顶点数据
//猜测是直接在顶点数据中定义好三角形索引顺序。
const vertices = new Float32Array([
    0.0, 0.0, 1.0,
    1.0, 0.0, 1.0,
    1.0, 1.0, 1.0,

    0.0, 1.0, 1.0,
    0.0, 0.0, 1.0,
    1.0, 1.0, 1.0
]);

// itemSize = 3 因为每个顶点都是一个三元组。
// geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
// const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
const mesh = createMesh(vertices, 0x0000FF, testCallback);// new THREE.Mesh( geometry, material );
scene.add(mesh);
mesh.position.x -= 10;

//使用顶点+索引+法向量创建mesh
const vertices2 = new Float32Array([
    0.0, 0.0, 1.0,
    1.0, 0.0, 1.0,
    1.0, 1.0, 1.0,
    0.0, 1.0, 1.0,
]);
const verticesIndex = new Uint16Array([
    0, 1, 2,
    3, 0, 2,
]);

const normals = new Float32Array([
    0, 0, 1, //顶点1法向量
    0, 0, 1, //顶点2法向量
    0, 0, 1, //顶点3法向量
    0, 0, 1, //顶点4法向量
]);
const mesh2 = createMeshSetIndex(vertices2, 0x00FF00, verticesIndex, normals);
mesh2.position.x
scene.add(mesh2);
mesh2.position.x += 10;

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

animate();
camera.position.z = 50;

function testCallback(msg) {
    console.log(msg);
    console.log("测试方法作为参数使用,对应c#委托事件功能");
}

//====================================================创建mesh方法封装==========================================
// 函数定义,参数不需要指定类型,返回值也不需要定义
//传入的顶点数组中定义好顶点索引
function createMesh(verticesArg, colorArg, callback) {
    let geometryTemp = new THREE.BufferGeometry();
    geometryTemp.setAttribute('position', new THREE.BufferAttribute(verticesArg, 3));
    const material = new THREE.MeshBasicMaterial({ color: colorArg });
    const mesh = new THREE.Mesh(geometryTemp, material);
    if (callback != null) {
        callback("mesh创建完毕");
    }
    return mesh;
}
//依据顶点、顶点索引、法向量创建mesh
function createMeshSetIndex(verticesArg, colorArg, indexs, normals) {
    let geometryTemp = new THREE.BufferGeometry();
    let ba = new THREE.BufferAttribute(verticesArg, 3);
    //配置顶点
    geometryTemp.setAttribute('position', ba);
    //配置法向量
    geometryTemp.attributes.normal = new THREE.BufferAttribute(normals, 3);
    //配置顶点索引
    geometryTemp.index = new THREE.BufferAttribute(indexs, 1);
    const material = new THREE.MeshBasicMaterial({ color: colorArg });
    const mesh = new THREE.Mesh(geometryTemp, material);
    return mesh;
}

原文地址:https://blog.csdn.net/chillxiaohan/article/details/136127294

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!