I am attempting to change the opacity of an object in the update function but I am not able to call on the object by name. It always returns undefined.
This code is a fragment. There are many cars using the same function. I commented, "IS THIS CORRECT?", for the questionable lines. Please comment if clarification is needed.
// ***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();