gpt4 book ai didi

javascript - 将纹理添加到自定义 three.js 几何

转载 作者:行者123 更新时间:2023-11-29 20:41:19 31 4
gpt4 key购买 nike

我一直在寻找一种在 three.js 中将 uv 映射添加到我的自定义几何体的方法。我找到了这样做的方法,但我找到的解决方案都没有用。谁能解释一下 uv-mapping 的工作原理以及如何正确使用它?

var s = 100;
var MapHeight = function(x, y, mult){
var map = new Array(x);
for(var i = 0; i < x; i++){
map[i] = new Array(y);
for (var j = 0; j < y; j++) {
map[i][j] = Math.sin((i*12+j)/10)*mult;
}
}
return map;
};
var heightMap = MapHeight(s, s, 0.3);
var loader = new THREE.TextureLoader();
var sandTex = loader.load("Textures/sand.jpeg");
var div = 2;
var Sand = function(color){
var geo = new THREE.Geometry();
var i;
for (i = 0; i < s; i++) {
for (var j = 0; j < s; j++) {
geo.vertices.push(new THREE.Vector3(i/div, heightMap[i][j], j/div));
}
}
for (i = 0; i < (s)*(s-1); i++) {
if (!Number.isInteger((i+1)/s)){
geo.faces.push(new THREE.Face3(i, i+1, i+s+1));
geo.faces.push(new THREE.Face3(i, i+s+1, i+s));
}
}
geo.computeVertexNormals();
geo.computeFaceNormals();
geo.center();
var mesh = new THREE.Mesh(
geo,
new THREE.MeshStandardMaterial({map: map})
);
return mesh;
};

现在,当我尝试向我的几何体添加 UV 贴图时,结果要么是黑色 Material ,要么我的程序无法运行。

最佳答案

必须将每个面的纹理坐标添加到第 1 层 UV 层。
参见 THREE.Geometry.faceVertexUvs

在 UV 层创建和排列:

geo.faceVertexUvs[0] = [];

并添加一个数组 3 THREE.Vector2对于每个三 Angular 形面:

geo.faceVertexUvs[0].push([
new THREE.Vector2(u0, v1),
new THREE.Vector2(u1, v1),
new THREE.Vector2(u2, v2)
]);

按如下方式将其应用于您的代码:

var geo = new THREE.Geometry();
var i;
var uv = [];
for (i = 0; i < s; i++) {
for (var j = 0; j < s; j++) {
geo.vertices.push(new THREE.Vector3(i/div, heightMap[i][j], j/div));
uv.push(new THREE.Vector2((i-1)/s, (j-1)/s));
}
}

geo.faceVertexUvs[0] = [];
for (i = 0; i < (s)*(s-1); i++) {
if (!Number.isInteger((i+1)/s)){

var vi = [i, i+1, i+s+1, i+s];

geo.faces.push(new THREE.Face3(vi[0], vi[1], vi[2]));
geo.faces.push(new THREE.Face3(vi[0], vi[2], vi[3]));

geo.faceVertexUvs[0].push([ uv[vi[0]], uv[vi[1]], uv[vi[2]] ]);
geo.faceVertexUvs[0].push([ uv[vi[0]], uv[vi[2]], uv[vi[3]] ]);
}
}
geo.computeVertexNormals();
geo.computeFaceNormals();

关于javascript - 将纹理添加到自定义 three.js 几何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55461909/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com