Vehicle Physics
Create physics-based vehicles with wheel constraints:
// This example uses Ammo.js which supports advanced vehicle physics
// Note: Vehicle physics implementation depends on the physics engine used
// Create a vehicle chassis
const chassisWidth = 2;
const chassisHeight = 0.6;
const chassisLength = 4;
const chassis = BABYLON.MeshBuilder.CreateBox("chassis", {
width: chassisWidth,
height: chassisHeight,
depth: chassisLength
}, scene);
chassis.position.y = 4;
// Create wheels
const wheelRadius = 0.4;
const wheelWidth = 0.3;
const wheelPositions = [
new BABYLON.Vector3(chassisWidth/2, -chassisHeight/2, chassisLength/2 - wheelRadius), // front right
new BABYLON.Vector3(-chassisWidth/2, -chassisHeight/2, chassisLength/2 - wheelRadius), // front left
new BABYLON.Vector3(chassisWidth/2, -chassisHeight/2, -chassisLength/2 + wheelRadius), // rear right
new BABYLON.Vector3(-chassisWidth/2, -chassisHeight/2, -chassisLength/2 + wheelRadius) // rear left
];
const wheels = [];
for (let i = 0; i < 4; i++) {
const wheel = BABYLON.MeshBuilder.CreateCylinder(`wheel${i}`, {
diameter: wheelRadius * 2,
height: wheelWidth,
tessellation: 24
}, scene);
wheel.rotation.z = Math.PI / 2; // Rotate to correct orientation
wheel.position = chassis.position.add(wheelPositions[i]);
wheels.push(wheel);
}
// Add physics
chassis.physicsImpostor = new BABYLON.PhysicsImpostor(
chassis,
BABYLON.PhysicsImpostor.BoxImpostor,
{ mass: 800, friction: 0.5, restitution: 0.2 },
scene
);
// Configure vehicle physics (Ammo.js specific)
// Note: Implementation details vary by physics engine
if (scene.getPhysicsEngine().getPhysicsPluginName() === "AmmoJSPlugin") {
const vehicle = new BABYLON.AmmoJSPlugin.Vehicle(chassis, scene);
// Add wheels to vehicle
for (let i = 0; i < 4; i++) {
const isFront = i < 2;
vehicle.addWheel(
wheels[i],
wheelPositions[i],
new BABYLON.Vector3(0, -1, 0), // Down direction
new BABYLON.Vector3(0, 0, 1), // Forward direction
0.6, // Suspension rest length
wheelRadius,
isFront // Steering wheel?
);
}
// Configure vehicle properties
vehicle.setSteeringValue(0.0); // Initial steering
vehicle.applyEngineForce(0.0); // Initial engine force
vehicle.setBrake(0.0); // Initial brake force
// Vehicle control with keyboard
scene.onKeyboardObservable.add((kbInfo) => {
const key = kbInfo.event.key;
const isDown = kbInfo.type === BABYLON.KeyboardEventTypes.KEYDOWN;
switch (key) {
case "w":
vehicle.applyEngineForce(isDown ? 1000 : 0);
break;
case "s":
vehicle.applyEngineForce(isDown ? -500 : 0);
break;
case "a":
vehicle.setSteeringValue(isDown ? 0.3 : 0);
break;
case "d":
vehicle.setSteeringValue(isDown ? -0.3 : 0);
break;
case " ":
vehicle.setBrake(isDown ? 50 : 0);
break;
}
});
}