[英]THREE javascript weird behavior when pushing mesh
忍受我,我是一个javascript和3个newby。 我在这里尝试在对象列表中推送网格的这段代码:
geometry = new THREE.BoxGeometry( 1, 50, 1 );
for ( var i = 0, l = geometry.faces.length; i < l; i ++ ) {
var face = geometry.faces[ i ];
face.vertexColors[ 0 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
face.vertexColors[ 1 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
face.vertexColors[ 2 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
}
for ( var i = 0; i < list.length; i=i+2 ) {
geometry.width = size_list[i];
geometry.depth = size_list[i+1];
console.log('geo');
console.log(geometry.width);
console.log(geometry.depth);
material = new THREE.MeshPhongMaterial( { specular: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors } );
var mesh = new THREE.Mesh( geometry, material );
mesh.position.x = list[i];
mesh.position.y = 5;
mesh.position.z = list[i+1];
console.log('mesh');
console.log(mesh.geometry.width);
console.log(mesh.geometry.depth);
scene.add( mesh );
material.color.setHSL( Math.random() * 0.2 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
objects.push( mesh );
}
所有网格都是大小不同的矩形。 大小存储在size_list
。 我只使用一个geometry
对象,因为如果使用更多的对象,则会导致程序崩溃。 我尝试通过移动每个网格来创建一个几何对象
geometry = new THREE.BoxGeometry( 1, 50, 1 );
for ( var i = 0, l = geometry.faces.length; i < l; i ++ ) {
var face = geometry.faces[ i ];
face.vertexColors[ 0 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
face.vertexColors[ 1 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
face.vertexColors[ 2 ] = new THREE.Color().setHSL( Math.random() * 0.3 + 0.5, 0.75, Math.random() * 0.25 + 0.75 );
}
进入第二个for循环,但浏览器无法处理。
因此,在创建网格并将其推到对象数组之前,我正在修改geometry
对象的属性。 我正在记录修改后的值,因此可以看到在打印好值时它们已正确更改。
但是,最后,在显示场景时,所有网格仍然具有如代码片段第一行中所定义的(1、50、1)尺寸。 我一直在阅读有关javascript的文章,我认为问题类似于处理副本和引用的方式,但我无法真正理解这种行为。
如何有效地修改网格而不必为每个网格创建一个新的geometry
对象? 为什么这种方法不起作用?
您可以通过设置网格的scale
属性来缩放网格。
使用此模式:
var geometry = new THREE.BoxGeometry( 1, 1, 1 ); // create once
然后在您的循环中:
var mesh = new THREE.Mesh( geometry, material ); // share the geometry
mesh.scale.set( width[ i ], height[ i ], depth[ i ] );
three.js r.73
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.