Physics Compounds
What is it
The Compound is a special type of shape that acts as a "container" for other shapes. It allows you to model complex objects by using simple primitives, achieving a better approximation than using only one simple geometric shape.
How to use
Imagine you have a mesh that represents a character. Character meshes are usually pretty complex, so we want to avoid using them directly for collision. We can approximate the shape of the character with a sphere representing the head and a box representing the rest of the body. We will create two meshes to represent these shapes, parent them to the character mesh, create two child physics shapes, and parent them to a PhysicsShapeContainer:
import { ImportMeshAsync } from "@babylonjs/core/Loading/sceneLoader";import { Quaternion, Vector3 } from "@babylonjs/core/Maths/math.vector";import { TransformNode } from "@babylonjs/core/Meshes/transformNode";import { PhysicsBody } from "@babylonjs/core/Physics/v2/physicsBody";import { PhysicsShapeBox, PhysicsShapeContainer, PhysicsShapeSphere } from "@babylonjs/core/Physics/v2/physicsShape";const myMesh = ImportMeshAsync(...);
const headNode = new TransformNode("headNode");headNode.position.y = 3;headNode.parent = myMesh;const bodyNode = new TransformNode("bodyNode");bodyNode.parent = myMesh;
const boxShape = new PhysicsShapeBox(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1), new Vector3(1, 2, 1), scene);const sphereShape = new PhysicsShapeSphere(new Vector3(0, 0, 0), 1, scene);
const parentShape = new PhysicsShapeContainer(scene);
parentShape.addChildFromParent(myMesh, boxShape, bodyNode);parentShape.addChildFromParent(myMesh, sphereShape, headNode);
const body = new PhysicsBody(myMesh, scene);body.shape = parentShape;The following Playground shows a simple example of creating a container body to approximate a mesh:
Simple Physics Container exampleThe following Playground shows a comparison of using Container, Convex Hull and Mesh shapes on different meshes:
Comparison of using Container, Convex Hull and Mesh shapes on different meshes