API

Aggregates

What is an Aggregate

The Physics Aggregate is an object that contains a body and a shape. It is a helper that allows you to create all the objects needed to physicalize your scene in just one call. In that sense, it is similar to Physics V1 Impostors, but with more control. Once created, you can easily access the individual parts and tweak them.

How to use it

import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder";
import { PhysicsShapeType } from "@babylonjs/core/Physics/v2/IPhysicsEnginePlugin";
import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate";
const sphere = MeshBuilder.CreateSphere("sphere", { segments: 16, diameter: 2 }, scene);
const aggregate = new PhysicsAggregate(sphere, PhysicsShapeType.SPHERE, { mass: 1 }, scene);

This is very similar to the Physics V1 Impostor. When the aggregate is created, a body and a shape are instantiated all at once. However, recreating shapes is not the most performant choice. You can instead pass the shape rather than the PhysicsShapeType, and the aggregate will reuse that shape:

import { MeshBuilder } from "@babylonjs/core/Meshes/meshBuilder";
import { PhysicsShapeType } from "@babylonjs/core/Physics/v2/IPhysicsEnginePlugin";
import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate";
const sphere = MeshBuilder.CreateSphere("sphere", { segments: 16, diameter: 2 }, scene);
const sphere2 = sphere.clone("sphere2");
const aggregate = new PhysicsAggregate(sphere, PhysicsShapeType.SPHERE, { mass: 1 }, scene);
const aggregate2 = new PhysicsAggregate(sphere2, aggregate.shape, { mass: 1 }, scene);
Reuse shapes with Aggregates Simple scene with Aggregate

Tweaking and accessing individual components

You can access the individual physics components by using the accessors:

import { PhysicsShapeType } from "@babylonjs/core/Physics/v2/IPhysicsEnginePlugin";
import { PhysicsAggregate } from "@babylonjs/core/Physics/v2/physicsAggregate";
const aggregate = new PhysicsAggregate(sphere, PhysicsShapeType.SPHERE, { mass: 1 }, scene);
aggregate.body.setMassProperties({ mass: 10 });

Disposing of an Aggregate

You can dispose of an aggregate by using the dispose method. This disposes of the body and the shape that were created by it, if the shape was created by the aggregate. If the shape was passed as a parameter, then it will not be disposed of, as it could still be in use by another body.

Further reading

Forces
Learn all about applying physical forces in Babylon.js.
Forces