簡體   English   中英

在three.js中為加載器創建可重用的函數

[英]Creating a reusable function for loaders in three.js

我試圖找到一種方法來創建可重用的函數,以防止我一次又一次地重復相同的加載器代碼。 可以在下面看到一個示例:

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(mesh);

arr.mesh [0] .position.x等

我也嘗試過退貨。

避免此類災難的最佳方法是什么?

處理重復代碼時,最常見和最簡單的方法是創建一個簡單函數

您的代碼示例:

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM