three.js - 三个Js更新顶点、法线和索引
问题描述
此代码呈现:
呈现代码
我遇到的问题是无法更新顶点,在我的代码中,我试图更新三个点以查看它是否有效。几何图形有一个法线向量和索引,所以也许我也应该更新它们。
export default (scene) => {
const noise = new Noise(Math.random());
const geometry = new THREE.BufferGeometry();
let indices = [];
let vertices = [];
let normals = [];
const size = 50;
const segments = 32;
const halfSize = size / 2;
const segmentSize = size / segments;
let xoff = 0,
yoff = 0,
zofff = 0.01;
for (let i = 0; i <= segments; i++) {
const y = i * segmentSize - halfSize;
yoff += 0.01;
for (let j = 0; j <= segments; j++) {
xoff += 0.01;
const dd = noise.perlin3(xoff, yoff, zofff) * 3;
const x = j * segmentSize - halfSize;
vertices.push(x, dd, -y);
normals.push(1, 0, 1);
}
}
for (let i = 0; i < segments; i++) {
for (let j = 0; j < segments; j++) {
const a = i * (segments + 1) + (j + 1);
const b = i * (segments + 1) + j;
const c = (i + 1) * (segments + 1) + j;
const d = (i + 1) * (segments + 1) + (j + 1);
// generate two faces (triangles) per iteration
indices.push(a, b, d); // face one
indices.push(b, c, d); // face two
}
}
geometry.setIndex(indices);
geometry.addAttribute(
'position',
new THREE.Float32BufferAttribute(vertices, 3).setDynamic(true),
);
geometry.addAttribute(
'normal',
new THREE.Float32BufferAttribute(normals, 3).setDynamic(true),
);
const material = new THREE.MeshPhongMaterial({
side: THREE.DoubleSide,
wireframe: true,
color: '0xffffff',
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
let zoff = 0;
function update() {
zoff += 0.1;
vertices[1] = Math.random() * 10;
vertices[4] = Math.random() * 10;
vertices[7] = Math.random() * 10;
mesh.geometry.attributes.position.needsUpdate = true;
mesh.geometry.verticesNeedUpdate = true;
}
解决方案
似乎,您必须使用位置而不是初始数组来更改缓冲区属性。因此,在您的更新中,它应该如下所示:
function update() {
zoff += 0.1; // the reason to have it here is unknown
geometry.attributes.position.setY(0, Math.random() * 10);
geometry.attributes.position.setY(1, Math.random() * 10);
geometry.attributes.position.setY(2, Math.random() * 10);
geometry.attributes.position.needsUpdate = true;
}
推荐阅读
- h.264 - 如何使用 AVFrame (Libav) 在 H264/265 解码中引用帧
- vue.js - Relative Tile Path in Vueleaflet
- node.js - d3 承诺立即开始 - 不等待数据
- javascript - 如何使用 3 选择列表创建过滤器选择列表
- vb.net - SMTP 身份验证遇到问题
- c# - 如何在.Net的GoogleWebAuthorizationBroker.AuthorizeAsync方法中发送存储为json字符串(在数据库中)的Google驱动器令牌?
- mysql - SQL 键相关错误
- .net - 无法替代
- asp.net-web-api - 第二次启动 ASP.NET Core 网站时 DLL 从 bin 中删除
- ios - IOS 构建因链接而失败