Make OBJ animate

Hello, i am trying two days now to animate an obj on click, but i can not find how to access the position of each obj. I have created a global js object that holds the objs, when i console.log the js objects, it prints ok.But when i console.log the individual is undefinied.

Here is the code:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
var controls = new THREE.OrbitControls( camera );
var renderer = new THREE.WebGLRenderer();
camera.position.set( 0, 20, 100 );
var myObjs={};
function init(){

controls.update();





var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );

var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.8);
ambientLight.position.y=-2;
				scene.add( ambientLight );
				var pointLight = new THREE.PointLight( 0xffffff, 1 );
				pointLight.position.y=-2;
				scene.add( pointLight );





				function addObject(model) {
				   var mtlLoader = new THREE.MTLLoader();
				   var objLoader = new THREE.OBJLoader();
					 var obj;
				   mtlLoader.load('Assets/'+model+'.mtl', function (materials) {
				    materials.preload();
				    objLoader.setMaterials(materials);

				    objLoader.load('Assets/'+model+'.obj', function (object) {

object.name = model;
myObjs[model]=object;

scene.add(myObjs[model]);


				    });
						});

				};


console.log(myObjs['window_R']);

console.log(myObjs.Fixed_window);


				addObject('window_R');
				addObject('Fixed_window');






camera.position.z =10;



renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement )


};


function animate() {
	var rotSpeed = 0.004;
	if(myObjs['window_R']){
myObjs['window_R'].rotation.y=+rotSpeed;
	}

	controls.update();
	requestAnimationFrame( animate );
	renderer.render( scene, camera );
}



animate();
init();

I created a fiddle for you that might be a useful help: https://jsfiddle.net/f2Lommf5/4042/

The problem is that the first log message (console.log(myObjs['window_R']);) happens at a point where your model is not loaded yet. Loading assets is an asynchronous operation. The log message would work if you place it in the onLoad() callback.

1 Like

Thanks, it helped me a lot