updateVehicle method

void updateVehicle(
  1. double timeStep
)

Implementation

void updateVehicle(double timeStep){
  final wheelInfos = this.wheelInfos;
  final numWheels = wheelInfos.length;
  final chassisBody = this.chassisBody;

  for (int i = 0; i < numWheels; i++) {
    updateWheelTransform(i);
  }

  currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.length();

  final forwardWorld = Vec3();
  getVehicleAxisWorld(indexForwardAxis, forwardWorld);

  if (forwardWorld.dot(chassisBody.velocity) < 0) {
    currentVehicleSpeedKmHour *= -1;
  }

  // simulate suspension
  for (int i = 0; i < numWheels; i++) {
    castRay(wheelInfos[i]);
  }

  updateSuspension(timeStep);

  final impulse = Vec3();
  final relpos = Vec3();
  for (int i = 0; i < numWheels; i++) {
    //apply suspension force
    final wheel = wheelInfos[i];
    double suspensionForce = wheel.suspensionForce;
    if (suspensionForce > wheel.maxSuspensionForce) {
      suspensionForce = wheel.maxSuspensionForce;
    }
    wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);

    wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
    chassisBody.applyImpulse(impulse, relpos);
  }

  updateFriction(timeStep);

  final hitNormalWorldScaledWithProj = Vec3();
  final fwd = Vec3();
  final vel = Vec3();
  for (int i = 0; i < numWheels; i++) {
    final wheel = wheelInfos[i];
    //final relpos = Vec3();
    //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
    chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel);

    // Hack to get the rotation in the correct direction
    int m = 1;
    //switch (indexUpAxis) {
    if (indexUpAxis == AxisIndex.y){
      m = -1;
      break;
    }

    if (wheel.isInContact) {
      getVehicleAxisWorld(indexForwardAxis, fwd);
      final proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
      wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);

      fwd.vsub(hitNormalWorldScaledWithProj, fwd);

      final proj2 = fwd.dot(vel);
      wheel.deltaRotation = (m * proj2 * timeStep) / wheel.radius;
    }

    if ((wheel.sliding || !wheel.isInContact) && wheel.engineForce != 0
    && wheel.useCustomSlidingRotationalSpeed) {
      // Apply custom rotation when accelerating and sliding
      wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
    }

    // Lock wheels
    if (wheel.brake.abs() > wheel.engineForce.abs()) {
      wheel.deltaRotation = 0;
    }

    wheel.rotation += wheel.deltaRotation ; // Use the old value
    wheel.deltaRotation *= 0.99 ; // damping of rotation when not in contact
  }
}