学习 Three.js (4) —— BufferGeometry()

three.js 中的几何体都是使用三角形构成的,而 BufferGeometry() 方法就是用于构建三角形的核心方法;这一篇来介绍如何使用 BufferGeometry() 来描绘一个几何体

// three.js
import * as THREE from "three";
// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";

// 创建场景
const scene = new THREE.Scene();

// 创建相机
const camera = new THREE.PerspectiveCamera(
  45,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
camera.updateProjectionMatrix();

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// 设置相机位置
camera.position.z = 10;
camera.position.y = 2;
camera.position.x = 2;
// 相机视角
camera.lookAt(0, 0, 0);

// 添加世界坐标辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);
// 设置带阻尼的惯性
controls.enableDamping = true;
// 设置阻尼系数
controls.dampingFactor = 0.05;
// 设置旋转速度
// controls.autoRotate = true;
controls.autoRotateSpeed = 10;

// 创建几何体
const geometry = new THREE.BufferGeometry();
// 创建顶点数据,逆时针顶点为正面
const vertices = new Float32Array([
  -1.0, -1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0,
]);

// 创建顶点属性
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));

geometry.setIndex(new THREE.BufferAttribute(indices, 1));

// 创建材质
const material1 = new THREE.MeshBasicMaterial({
  color: "#ff7700",
  wireframe: false,
  side: THREE.DoubleSide,
});
const material2 = new THREE.MeshBasicMaterial({
  color: "#fff",
  wireframe: false,
  side: THREE.DoubleSide,
});

geometry.addGroup(0, 3, 1);
geometry.addGroup(3, 3, 0);

const plane = new THREE.Mesh(geometry, [material1, material2]);

scene.add(plane);

// 渲染函数
const animate = () => {
  controls.update();

  // 渲染场景
  renderer.render(scene, camera);
  requestAnimationFrame(animate);
};

animate();

// 重置窗口大小
window.addEventListener("resize", () => {
  // 重置渲染器宽高比
  renderer.setSize(window.innerWidth, window.innerHeight);
  // 重置相机宽高比
  camera.aspect = window.innerWidth / window.innerHeight;
  // 更新相机投影矩阵
  camera.updateProjectionMatrix();
});

你可能感兴趣的:(Three.js,学习,javascript,贴图,开发语言,前端,vscode)