Can not read position of undefined at animate

Hello,

I’m trying to load a collada object and move it forward by changing its position in animate() but I have this error : Cannot read ‘position’ of undefined at animate. I don’t understand, it is the first time I have this error.

That’s what I do :
I declare my var mario outside of all functions :

var mario;
init();
animate(); 

In init I call my function to load a collada :

CreateObject(mario,"dae/mario.dae",50,50,50,0,-28,0,0);

CreateObject :

function CreateObject(object,src,size1, size2, size3, posX,posY, posZ, rotation,audio){				
            // loading manager
            var loadingManager = new THREE.LoadingManager( function () {
				scene.add( object );
			});
			// collada
			var loader = new THREE.ColladaLoader( loadingManager );
			loader.load( src, function ( collada ) {
				object = collada.scene;
                object.scale.set(size1,size2,size3); //Objet permettant de donner une taille à la maison
                object.position.x = posX;
                object.position.y = posY;
                object.position.z = posZ;
                object.rotation.z = rotation;
				object.traverse(function (child) {//on ajoute les ombres

					if (child instanceof THREE.Mesh) {
						child.castShadow = true;
						child.receiveShadow = true;
					}
				});
                if(audio)
               		object.add(audio);
			});				
        }

And then in animate I try to move the collada :

    function animate() {
		 requestAnimationFrame( animate );
			mario.position.x += 3;
                            //etc
    }

Can someone help me please ?

Thank you.

Hi!
Try something like this:

function animate() {
    requestAnimationFrame( animate );
    if (mario) {
        mario.position.x += 3;
        //etc
    }
}

Loading a file is asynchronous, thus, you try to access mario variable when it’s still undefined.
IMHO, it’s better to load all resources first, then run an animation loop.

Hi, thank you ! My error is gone.

However, my object is not moving, I tried a console.log in if(mario) but nothing happened.

It looks like my object is never defined…

You can take a look at the official examples and compare their source code with yours :slight_smile:
https://threejs.org/examples/?q=collada#webgl_loader_collada_skinning

Ok thank you so you don’t have any idea about the problem that my object is never defined ?

Do you have a working live code example? jsfiddle, codepen ect. :slight_smile:

I have never used this before but I can try, I just don’t know how to upload file I need to run the code.

I use github for that purpose.

Ok, can I just send you my entire code or do you need to test ?

You can try to archive it and share the archive in this thread :slight_smile:
Thus not only me could try to help you.

The solution was to load the collada in init(); nevertheless, I haven’t found how to load object and move it just by one function.