Apply Engine Force to Ammo.js Vehicle Wheels

This article explains how to apply engine force to specific wheels of a raycast vehicle using the ammo.js physics library. You will learn how wheel indexing works within the btRaycastVehicle class and how to programmatically control individual wheels to configure rear-wheel, front-wheel, or all-wheel drive systems.

Understanding Wheel Indices

In ammo.js, wheels are referenced by a zero-based index. The index of a wheel is determined by the order in which you added it to the vehicle using the addWheel method.

Typically, wheels are added in the following order: * Index 0: Front-Left Wheel * Index 1: Front-Right Wheel * Index 2: Rear-Left Wheel * Index 3: Rear-Right Wheel

If your vehicle setup script adds the wheels in a different order, your indices will change accordingly. Always match your drive logic to the exact sequence in which your wheels were registered.

Using the applyEngineForce Method

To apply power to a wheel, use the applyEngineForce method on your btRaycastVehicle instance. This method takes two arguments:

  1. Force (Number): The amount of torque/force to apply. Positive values move the vehicle forward, while negative values move it in reverse.
  2. Wheel Index (Integer): The index of the wheel to which the force should be applied.
// Syntax: vehicle.applyEngineForce(force, wheelIndex);
vehicle.applyEngineForce(1000, 2); 

Implementing Drive Configurations

Depending on your physics requirements, you can apply force to specific wheels to create different drivetrain layouts.

Rear-Wheel Drive (RWD)

To power only the rear wheels (typically indices 2 and 3), apply the force to those specific indices while setting the front wheels (0 and 1) to zero engine force.

const force = 1500; // Define your engine force

// Apply force to rear wheels
vehicle.applyEngineForce(force, 2); // Rear-Left
vehicle.applyEngineForce(force, 3); // Rear-Right

// Ensure no engine force is on the front wheels
vehicle.applyEngineForce(0, 0); 
vehicle.applyEngineForce(0, 1);

Front-Wheel Drive (FWD)

To power only the front wheels, apply the force to indices 0 and 1.

const force = 1500;

// Apply force to front wheels
vehicle.applyEngineForce(force, 0); // Front-Left
vehicle.applyEngineForce(force, 1); // Front-Right

// Ensure no engine force is on the rear wheels
vehicle.applyEngineForce(0, 2);
vehicle.applyEngineForce(0, 3);

All-Wheel Drive (AWD)

To distribute power to all wheels, loop through every wheel index and apply the force. You can split the force equally or distribute it based on a front/back bias.

const force = 1000;

// Apply equal force to all four wheels
for (let i = 0; i < 4; i++) {
    vehicle.applyEngineForce(force, i);
}

Important Considerations