/// <summary> /// Handle train physics update /// /// </summary> public void FixedUpdate() { //Call if we are the first in the train if (previous == null) { if (isDerailed) { var r = GetComponent <Rigidbody>(); if (r != null) { _velocity = r.velocity.magnitude; } return; } float trainBrakeForce = 0; float trainMass = 0; float trainEngineForce = 0; float trainDragForce = 0; TrainController trailer = this; while (trailer != null) { trainBrakeForce += trailer.GetBrakeForce(); trainMass += trailer.GetMass(); trainDragForce += trailer.GetDragForce(); TrainEngineController engine = trailer as TrainEngineController; if (engine != null) { trainEngineForce += engine.GetTractiveForce(); } trailer = trailer.next; } //Debug.Log("Train Mass " + trainMass + " kg"); // Add engine effort Velocity += (trainEngineForce / trainMass) * Time.fixedDeltaTime; // Calculate and subtract drag and braking float brakeValue = -(float)trackVehicle.direction * (trainBrakeForce / trainMass) * Time.fixedDeltaTime; trainDragForce *= -(float)trackVehicle.direction; // Combine drag and brake into single value float dragValue = brakeValue + (trainDragForce / trainMass) * Time.fixedDeltaTime; // Stop train from reversing due to brake force... if (trackVehicle.direction == Direction.Forward && Velocity + dragValue < 0.0f) { Velocity = 0.0f; } else { Velocity += dragValue; } //Set the velocity on the entire train TrainController t = next; while (t != null) { t.Velocity = Velocity; t = t.next; } // Update positions OnFixedUpdate(); } }