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