[英]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.