Forces and Impulses
Apply physics forces to objects in your scene:
// In Physics V2, access the PhysicsBody via the aggregate
// Apply a continuous force (newtons)
sphereAggregate.body.applyForce(
new BABYLON.Vector3(0, 0, 10), // Force direction and magnitude
sphere.getAbsolutePosition() // Application point
);
// Apply an impulse (instantaneous force)
boxAggregate.body.applyImpulse(
new BABYLON.Vector3(5, 0, 0), // Impulse direction and magnitude
box.getAbsolutePosition() // Application point
);
// Set linear velocity directly
sphereAggregate.body.setLinearVelocity(new BABYLON.Vector3(0, 5, 0));
// Set angular velocity (rotation)
boxAggregate.body.setAngularVelocity(new BABYLON.Vector3(0, 2, 0));Create user-controlled physics interactions:
// Add force on key press (Physics V2)
scene.onKeyboardObservable.add((kbInfo) => {
if (kbInfo.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
const body = sphereAggregate.body;
const pos = sphere.getAbsolutePosition();
switch (kbInfo.event.key) {
case "ArrowUp":
body.applyImpulse(new BABYLON.Vector3(0, 0, -10), pos);
break;
case "ArrowDown":
body.applyImpulse(new BABYLON.Vector3(0, 0, 10), pos);
break;
case "ArrowLeft":
body.applyImpulse(new BABYLON.Vector3(-10, 0, 0), pos);
break;
case "ArrowRight":
body.applyImpulse(new BABYLON.Vector3(10, 0, 0), pos);
break;
case " ": // Space key
body.applyImpulse(new BABYLON.Vector3(0, 10, 0), pos);
break;
}
}
});