0

我试图在更新函数中更改对象的不透明度,但我无法按名称调用对象。它总是返回未定义的。

这段代码是一个片段。有许多汽车使用相同的功能。对于有问题的台词,我评论说:“这是正确的吗?”。如果需要澄清,请发表评论。

// ***Program starts at the bottom

// initialize the scene
function init() {
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(45, window.innerWidth/window.innerHeight, 1, 1000);
    camera.position.set(-71, 29, 103);

    getCarAnim('Car1');
    scene.add(parentCar1);
    update(renderer, scene, camera);
    return scene;
}

// importing the car model
function getCarAnim(path) {
    var objLoader = new THREE.OBJLoader();
    objLoader.load('/resource/3D Models/' + path + '.obj', function (obj) {
        obj.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
            child.material = carMaterial;
            child.material.transparent = true;
            if (path == 'Car1') { // IS THIS CORRECT?
                child.name = "Car1";
            }
        }
    });

    if (path == 'Car1') {
        parentCar1.add(obj);
        parentCar1.position.x = 15;
        parentCar1.position.y = 0.9;
        parentCar1.position.z = 3;
    }
}

// rendering/updating the frame to screen
function update (renderer, scene, camera) {
    renderer.render(scene, camera);
    if (parentCar1.position.x <= 15) {
        parentCar1.getObjectByName("Car1").material.opacity = .2; // IS THIS CORRECT?
    }
    requestAnimationFrame(function() {
        update(renderer, scene, camera);
    })
}

//**** program starts here

// This variable is the parent of the imported car model.
// It allows an imported object to be called upon
// so it can be animated in the update function.
var parentCar1 = new THREE.Object3D;

var carMaterial = new THREE.MeshLambertMaterial({color: 'rgb(152,152,152)'});
var scene = init();
4

0 回答 0