Game Development Reference
In-Depth Information
Model and ModelInstances
A model represents a 3D asset. It stores a hierarchy of nodes. A node has a transform
and optionally a graphical part in the form of a
MeshPart
and
Material
. A model
can be rendered by creating
ModelInstance
from it. This instance has an additional
transform to position the model in the world, and allows the modification of
materials and nodes without destroying the original model. The original model is the
owner of any meshes and textures; all instances created from the model share these
resources. Disposing of the model will automatically make all instances invalid.
We create a sphere model using LibGDX's
ModelBuilder
. It can create basic shapes
such as box, sphere, cone, capsule, cylinder, and so on, as follows:
public Model model;
public ModelInstance instance;
ModelBuilder modelBuilder = new ModelBuilder();
model = modelBuilder.createSphere(2, 2, 2, 20, 20,
new Material(ColorAttribute.createDiffuse(Color.YELLOW)),
Usage.Position | Usage.Normal);
instance = new ModelInstance(model);
In the preceding code, a sphere is created with the width, height, and depth set to
2
units and the horizontal and vertical divisions are set to
20
. You have to provide
materials and attributes to create any model. Finally,
ModelInstance
is created from
that model. After using the model, we dispose of it by calling
model.dispose()
.
The ModelBatch class
The
ModelBatch
class is used to render the model instance as follows:
modelBatch.begin(cam);
modelBatch.render(instance, environment);
modelBatch.end();
In the render method, we clear the screen, call
modelBatch.begin()
, render our
ModelInstance
, and then call
modelBatch.end()
to finish rendering. While
rendering the model using
modelBatch.render()
, we provide the environment
along with the rendering
ModelInstance
. The model batch is disposed of by calling
modelBatch.dispose()
.