Skip to content Skip to sidebar Skip to footer

How To Make A Json Model Auto-rotates In The Scene?

I can rotate the ballmesh when I use mouseevent. First try var jsonLoader = new THREE.JSONLoader(); jsonLoader.load('models/ball.json', addJsonToScn); function addJsonToScn(geome

Solution 1:

What you're struggling here has nothing to do with three.js, but the fact that JavaScript provides an event-driven environment, and you need to consider when sections of code are executed in reality.

In this particular example, you're sending a call out to request that a model is loaded, plus you attach an "on completion" event to that request. Even though you register it here, that event handler code which will only be executed after the model is loaded and processed.

Right after that request is sent your main code continues and starts animating the scene. But that completion event hasn't been executed yet (the model is still loading), and you get that undefined variable error.

At some point after that, your model will be loaded, and the event handler attached to that code will now set that variable ... but your animation loop has already broken because of the undefined variable.

The most trivial way to work around the problem for your particular example is to ignore the mesh until it is ready:

functionanimate() {
    if ( ballmesh !== undefined ) {
         ballmesh.rotation.y += 0.1;
    }
    requestAnimationFrame( animate );
    renderer.render( scene, camera );
}

Another way might be to start your animation loop from the addJsonToScn event handler, though that basic approach will only work well for trivial examples like these where you only want to wait on a single load event.

Post a Comment for "How To Make A Json Model Auto-rotates In The Scene?"