Game Development Reference
In-Depth Information
Managing loaders
Right now, when our CTF map is initialized, we ask a loader to fetch the flag model.
This works fine because the model is pretty small and we only have the one model to
load. However, if we had many models or if they were bigger, we may notice them
popping into the map when they finished loading, even after we've started playing.
To fix this, larger projects should preload assets before the player can start playing the
game. All that's required to do so is to disallow entering the map until the last model's
callback has been executed. Unfortunately, if we have a lot of models and we have to
load them one by one, it can be hard to keep track of how many models are remaining.
Users may also lose interest if nothing is happening while models are loading.
Usually, this is resolved by loading all the models at once with the
SceneLoader
.
The
SceneLoader
objects have a
callbackProgress
property that holds a function
which is invoked after each object in the scene has completed loading. The callback
takes two parameters,
progress
and
result
. The
progress
object has four numeric
properties that can be used to display a progress bar:
totalModels
,
totalTextures
,
loadedModels
, and
loadedTextures
. The result object contains all of the entities
that have been loaded so far, and it's also the value passed to the
onLoad
parameter
of the loader's
load
callback when all loading has been completed.
Consider HTML like this for a loading bar, where the outer div has a defined width:
<div id="bar"><div id="progress"></div></div>
In this case, you might include code like this in a
callbackProgress
handler:
var total = progress.totalModels + progress.totalTextures,
loaded = progress.loadedModels + progress.loadedTextures,
progressBar = document.getElementById('progress');
progressBar.style.width = Math.round(100 * loaded / total) + '%';
If you can't use a
SceneLoader
or don't want to use it for other reasons, you will
have to chain together your loaders manually. However, Three.js will start using
loading managers
in the future. Loading managers are just objects that work
together with loaders to track when multiple resources have finished loading.
The loading manager API is not yet stable as of Three.js version r61 and it is not
implemented in many of the loaders.