Javascript Three.js - 在运行时更改材质

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12564156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:43:20  来源:igfitidea点击:

Three.js - Change Material on Runtime

javascript3dwebglthree.js

提问by Phipps

I have some .js files exported from Blender and load them with THREE.JSONLoader();

我有一些从 Blender 导出的 .js 文件并加载它们 THREE.JSONLoader();

my callback:

我的回调:

var callback   = function( geometry ) { createMesh(geometry);

my loading:

我的加载:

loader.load( "Models/sculp.js", callback );

my create method:

我的创建方法:

function createMesh(geometry){

    inArr[id] = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial( { color: 0xbbbbbb} ) );
    inArr[id].scale.set( 100, 100, 100 );
    scene.add( inArr[id] );
    id++;
}

Now I want to change my material on runtime by using my keyboard (changes color and opacity).

现在我想通过使用我的键盘在运行时更改我的材质(更改颜色和不透明度)。

How can I do that?

我怎样才能做到这一点?

回答by kaipr

As you create a new material for each mesh I assume you only want to change the color of one mesh and not of all in the inArrarray, and you probably need some sort of select for that. But changing the color of the material alone is quite easy:

当您为每个网格创建新材质时,我假设您只想更改一个网格的颜色,而不是inArr数组中所有网格的颜色,并且您可能需要为此进行某种选择。但是单独改变材料的颜色很容易:

var onKeyDown = function(event) {
  if (event.keyCode == 67) { // when 'c' is pressed
    object.material.color.setHex(0xff0000); // there is also setHSV and setRGB
  }
};
document.addEventListener('keydown', onKeyDown, false);

objectis the mesh you want to change. Key codes can be found here: http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

object是您要更改的网格。关键代码可以在这里找到:http: //www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes