我试图找到一种方法来创建一个可重用的函数,阻止我一遍又一遍地重复相同的加载器代码。下面是一个例子:
one = new THREE.Group();
var loader1 = new THREE.TextureLoader();
loader1.crossOrigin = '';
loader1.load('',
function (texture) {
this.geo = new THREE.BoxGeometry(10,10,10);
this.mat = new THREE.MeshBasicMaterial({color:'white'});
this.mesh = new THREE.Mesh(this.geo, this.mat);
one.add(mesh)
}
);
twp = new THREE.Group();
var loader2 = new THREE.TextureLoader();
loader2.crossOrigin = '';
loader2.load('',
function (texture) {
this.geo = new THREE.BoxGeometry(10,10,10);
this.mat = new THREE.MeshBasicMaterial({color:'white'});
this.mesh = new THREE.Mesh(this.geo, this.mat);
two.add(mesh)
}
);
我的尝试如下:
example = new THREE.Group();
function reuse(obj) {
this.loader = new THREE.TextureLoader();
this.loader.crossOrigin = '';
this.loader.load('',
function (texture) {
this.geo = new THREE.BoxGeometry(10,10,10);
this.mat = new THREE.MeshBasicMaterial({color:'white'});
this.mesh = new THREE.Mesh(this.geo, this.mat);
obj.name.add(mesh)
}
)
};
var test = new reuse({name: 'example'});
我还尝试在函数中的数组中推送网格:
arr.push(目);
arr.mesh [0] .position.x 等
我也尝试过它。
避免此类灾难的最佳方法究竟是什么?
答案 0 :(得分:1)
处理重复代码时,最常见也是最简单的方法是创建一个简单的函数
代码示例:
function getTexturedCube(path){
var geometry = new THREE.BoxGeometry(10,10,10);
var loader = new THREE.TextureLoader();
//you dont have to put onLoad function in,
//the texture returned will automatically update when it is loaded
var texture = loader.load(path);
var material = new THREE.MeshBasicMaterial({map:texture});
return new THREE.Mesh(geometry, material)
}
var group = new THREE.Group();
var cube1 = getTexturedCube("/path/to/image");
var cube2 = getTexturedCube("/path/to/other/image");
group.add(cube1);
group.add(cube2);
var anotherGroup = new THREE.Group();
var cube3 = getTexturedCube("/path/to/yet/another/image")
anotherGroup.add(cube3);
你也可以将函数传递给你的组,并让它将对象推入其中
function addTexturedCube(path, object){
var geometry = new THREE.BoxGeometry(10,10,10);
var loader = new THREE.TextureLoader();
var texture = loader.load(path);
var material = new THREE.MeshBasicMaterial({map:texture});
object.add(new THREE.Mesh(geometry, material));
}
var group = new THREE.Group();
addTexturedCube("/path/to/image", group);
addTexturedCube("/path/to/other/image", group);