flutter3d
Showcase Changelog 62 packages API reference

A car on four springs

since 1.0.0-rc.1 Physics and particles

A vehicle on the physics core is an ordinary dynamic body, the chassis, with up to eight wheels under it. The wheels are not bodies. Each step, every wheel casts a ray straight down from where its suspension is fixed. Where the ray lands, a spring and a damper hold the chassis up, the drive and the brake push it along the road, and the tyre holds it from sliding sideways. The chassis still collides, rolls over and sleeps like anything else.

This page drives a car round a loop on a flat road with a plank across it. Steer it, change its speed, brake, or put it on ice.

Step 1: A road and a chassis #

The road is a fixed box, and so is the plank. The chassis is a box of 1200 kg, 1.8 m wide, 0.6 m tall and 4 m long, a metre above the road at the start. Nothing about it says yet that it is a car.

/// A floor, a plank across the loop, and a chassis of 1200 kg at the
/// start, facing +z.
void _restart() {
  _world?.dispose();
  final NativeWorld? world = _world = _open();
  if (world == null) return;
  final NativeBody floor = world.addBody(
    position: Vector3(0.0, -0.5, 0.0),
    type: NativeBodyType.fixed,
    mass: 0.0,
  );
  world.setShape(floor, NativeShape.box(Vector3(60.0, 0.5, 60.0)));
  final NativeBody plank = world.addBody(
    position: _plank,
    type: NativeBodyType.fixed,
    mass: 0.0,
  );
  world.setShape(plank, NativeShape.box(Vector3(2.0, 0.04, 0.3)));
  final NativeBody chassis = _chassis = world.addBody(
    position: Vector3(0.0, 1.0, 0.0),
    mass: _mass,
  );
  world.setShape(chassis, NativeShape.box(Vector3(0.9, 0.3, 2.0)));
  _fit();
}

Step 2: Four wheels under it #

createVehicle makes the chassis a car and says which of its own axes are up and forward. Up is where the springs push and the axis a wheel steers about; forward is the way a wheel rolls. Each wheel is fixed to the chassis at a point in the chassis's own frame. It has a suspension 0.4 m long at rest, a radius of 0.35 m, a spring of 30 000 N/m, a damper of 3000 N s/m and a grip, the friction coefficient between tyre and road.

The grip is set when a wheel is made. Picking Ice takes the car's vehicle out and fits it again with a grip of 0.1 instead of 1, on the same chassis, moving as it was.

/// Puts the car's four wheels under its chassis, for the road's grip.
/// Up is the chassis's +y and forward its +z; wheels 0 and 1 are the
/// front pair, right then left, and 2 and 3 the rear.
void _fit() {
  final NativeWorld world = _world!;
  final NativeBody chassis = _chassis!;
  if (_car case final NativeVehicle old) world.removeVehicle(old);
  final NativeVehicle car = _car = world.createVehicle(
    chassis,
    up: Vector3(0.0, 1.0, 0.0),
    forward: Vector3(0.0, 0.0, 1.0),
  );
  for (final (double x, double z) in const <(double, double)>[
    (-0.8, 1.3),
    (0.8, 1.3),
    (-0.8, -1.3),
    (0.8, -1.3),
  ]) {
    world.addWheel(
      car,
      NativeWheelSettings(
        attach: Vector3(x, -0.2, z),
        rest: 0.4,
        radius: 0.35,
        stiffness: _stiffness,
        damping: 3000.0,
        grip: icy ? 0.1 : 1.0,
      ),
    );
  }
}

Step 3: A driver #

setWheel is what a driver asks of one wheel: a steering angle in radians, positive to the left, a drive force in newtons and a brake force. It holds until it is set again. This driver sets all four every step. The front wheels steer about one point on the line of the rear axle, so the inner wheel turns more than the outer one. With both at the same angle they would scrub against each other through every turn. The rear wheels push in proportion to how far the car is under the speed it was asked for, up to 2400 N each.

/// One step of the driver, then one of the world. The front wheels steer
/// about the same point on the line of the rear axle, the inner one more;
/// the rear wheels push to hold [speed]; the brake holds all four.
void _drive() {
  final NativeWorld world = _world!;
  final NativeVehicle car = _car!;
  final NativeBody chassis = _chassis!;
  var right = 0.0;
  var left = 0.0;
  if (steer != 0.0) {
    final double radius = _wheelbase / math.tan(steer);
    right = math.atan(_wheelbase / (radius + _track / 2));
    left = math.atan(_wheelbase / (radius - _track / 2));
  }
  final Vector3 forward = world
      .orientationOf(chassis)
      .asRotationMatrix()
      .transformed(Vector3(0.0, 0.0, 1.0));
  final double going = world.velocityOf(chassis).dot(forward);
  final double push = braking
      ? 0.0
      : (800.0 * (speed - going)).clamp(-2400.0, 2400.0);
  final double brake = braking ? 4000.0 : 0.0;
  world
    ..setWheel(car, 0, steer: right, brake: brake)
    ..setWheel(car, 1, steer: left, brake: brake)
    ..setWheel(car, 2, drive: push, brake: brake)
    ..setWheel(car, 3, drive: push, brake: brake)
    ..step(_step);
}

Step 4: Drawing the wheels #

wheelsOf answers each wheel as the last step left it: whether it touches the road, its suspension's length, its centre, how far it has turned about its axle, its spring's force, how fast it is sliding sideways, and its skid, which is how far past its grip the tyre was asked to go. The car is drawn from that. Each wheel sits at its centre, turned by its steering and its rotation, and its tyre goes red as it skids. On tarmac the tyres stay black except for a moment over the plank. On ice the rear wheels spin under the drive and the car slides wide of the turn it is steered into.

/// The chassis where the core has it, and each wheel at its centre,
/// turned by its steering about the chassis's up and by its rotation
/// about its axle. A tyre past its grip turns red.
void _place(DemoContext context) {
  final NativeWorld? world = _world;
  if (world == null) return;
  final Vector3 at = world.localPositionOf(_chassis!);
  final Quaternion turn = world.orientationOf(_chassis!);
  final Matrix3 frame = turn.asRotationMatrix();
  final Vector3 roof = at + frame.transformed(Vector3(0.0, 0.5, -0.3));
  _body
    ..setPositionFrom(at)
    ..setRotation(turn);
  _cabin
    ..setPositionFrom(roof)
    ..setRotation(turn);
  final List<NativeWheelState> wheels = world.wheelsOf(_car!);
  for (var i = 0; i < wheels.length; i++) {
    final NativeWheelState w = wheels[i];
    final Quaternion rolled =
        turn *
        Quaternion.axisAngle(Vector3(0.0, 1.0, 0.0), w.steer) *
        Quaternion.axisAngle(Vector3(1.0, 0.0, 0.0), w.rotation);
    _spokes[i]
      ..setPositionFrom(w.center)
      ..setRotation(rolled);
    _tireSet[i]
      ..setPositionFrom(w.center)
      // The cylinder stands along its y; its axle is the wheel's x.
      ..setRotation(
        rolled * Quaternion.axisAngle(Vector3(0.0, 0.0, 1.0), math.pi / 2),
      );
    final double slide = math.min(w.skid, 1.0);
    _tyrePaint[i].baseColor = LinearColor.fromSrgb(
      0.08 + 0.8 * slide,
      0.08,
      0.08,
      1.0,
    );
  }
  context.orbit.target.setValues(at.x, 0.8, at.z);
  context.orbit.apply();
}

Step 5: What the car should do #

On tarmac with nothing asked of it, the car settles in three seconds with all four wheels down, at the height the springs put it. Each spring holds a quarter of the weight, so it is squeezed by m g / 4k, about 0.1 m. Driven straight for two seconds it goes forward and not sideways. Steered left for a second and a half it ends to the left, facing left, still turning that way.

// On tarmac, standing still for three seconds: each spring holds a
// quarter of the weight, squeezed m g / 4k from its rest length, which
// puts the chassis 0.2 + 0.35 + 0.4 m, less that, over the road.
icy = false;
braking = false;
steer = 0.0;
speed = 0.0;
_restart();
drive(180);
final double squeeze = _mass * _world!.gravityMagnitude / 4 / _stiffness;
final double height = _pose.at.y;
if ((height - (0.95 - squeeze)).abs() > 3e-3) {
  throw StateError('the chassis rests at $height, not ${0.95 - squeeze}');
}
if (!_world!.wheelsOf(_car!).every((w) => w.touching)) {
  throw StateError('a wheel at rest is off the road');
}
// Two seconds asking for 5 m/s, straight: forward along +z, and not
// sideways. The core gets 5.9 m.
speed = 5.0;
drive(120);
final Vector3 straight = _pose.at;
if (straight.z < 4.0 || straight.x.abs() > 0.05) {
  throw StateError('driving straight ended at $straight');
}
// A second and a half steered 0.2 rad to the left: left of a car facing
// +z with +y up is +x, and it has turned that way, about +y. The core
// ends 2.3 m to the left, facing 0.51 of the way round to +x.
steer = 0.2;
drive(90);
final turned = _pose;
final double yaw = _world!.angularVelocityOf(_chassis!).y;
if (turned.at.x < 1.0 || turned.forward.x < 0.3 || yaw < 0.2) {
  throw StateError(
    'steering left ended at ${turned.at}, facing ${turned.forward}, '
    'turning at $yaw rad/s',
  );
}

Note. The tyres are a friction circle solved once per step: eight passes over the wheels, through the chassis's mass and inertia, and the forces they settle on are held for the whole step. There is no tyre model beyond that, so no slip angle curve or load sensitivity. The wheels are rays, one down the middle of each wheel. A kerb narrower than the wheel but beside that ray is never seen, and an edge the ray crosses lifts the wheel at once, with no rounding over it.