95 lines
3.0 KiB
C#
95 lines
3.0 KiB
C#
using Godot;
|
|
using System;
|
|
|
|
public partial class PhysicsManager : Node2D
|
|
{
|
|
private const double TARGET_DT = 1.0 / 2000.0;
|
|
private const double VALUE_SENSITIVITY = 5;
|
|
|
|
private double _accumulator = 0.0;
|
|
private double _simulationTime = 0.0;
|
|
|
|
private double _rpmSmooth = 0, _powerSmooth = 0, _throttleSmooth = 0;
|
|
|
|
private Label _rpmLabel, _powerLabel, _throttleLabel;
|
|
|
|
private Engine _engine;
|
|
|
|
[Export] public ProceduralEngine EngineAudio;
|
|
|
|
public override void _Ready()
|
|
{
|
|
_rpmLabel = GetNode<Label>("UI/EngineRPM");
|
|
_powerLabel = GetNode<Label>("UI/EnginePower");
|
|
_throttleLabel = GetNode<Label>("UI/EngineThrottle");
|
|
|
|
_engine = new Engine(inertia: 0.2, cylinders: 1, displacementCC: 1998, compressionRatio: 10.5);
|
|
_engine.MomentOfInertia = 0.4;
|
|
|
|
// --- Audio initialization ---
|
|
if (EngineAudio != null)
|
|
{
|
|
EngineAudio.CylinderCount = _engine.CylinderCount;
|
|
EngineAudio.EngineLayout = "v";
|
|
EngineAudio.IsCrossplane = true;
|
|
EngineAudio.BaseEngineVolume = 0.35f;
|
|
EngineAudio.IntakeRoarAmount = 0.28f;
|
|
EngineAudio.IntakeHissAmount = 0.12f;
|
|
EngineAudio.ExhaustRumbleAmount = 0.32f;
|
|
EngineAudio.ExhaustCrackleAmount = 0.08f;
|
|
|
|
EngineAudio.ResetAudioState();
|
|
|
|
EngineAudio.CurrentRPM = 750f;
|
|
EngineAudio.CurrentThrottle = 0f;
|
|
EngineAudio.CurrentCombustionPower = 0f;
|
|
|
|
if (!EngineAudio.Playing)
|
|
EngineAudio.Play();
|
|
|
|
EngineAudio.PrewarmBuffer();
|
|
}
|
|
}
|
|
|
|
public override void _Process(double dt)
|
|
{
|
|
bool wPressed = Input.IsKeyPressed(Key.W);
|
|
|
|
double throttle = wPressed ? 1.0f : 0.0f;
|
|
_engine.Ecu.Throttle = throttle;
|
|
|
|
double safeDelta = Math.Min(dt, 0.025);
|
|
_accumulator += safeDelta;
|
|
while (_accumulator >= TARGET_DT)
|
|
{
|
|
SimulateStep(TARGET_DT);
|
|
_simulationTime += TARGET_DT;
|
|
_accumulator -= TARGET_DT;
|
|
}
|
|
|
|
_rpmSmooth = Util.Lerp(_rpmSmooth, _engine.RPM, VALUE_SENSITIVITY * dt);
|
|
_powerSmooth = Util.Lerp(_powerSmooth, _engine.CurrentPower/1000, VALUE_SENSITIVITY * dt);
|
|
_throttleSmooth = Util.Lerp(_throttleSmooth, _engine.ThrottlePosition * 100, VALUE_SENSITIVITY * dt);
|
|
|
|
_rpmLabel.Text = $"RPM: {_rpmSmooth:F0}";
|
|
_powerLabel.Text = $"Power: {_powerSmooth:F2} Kw";
|
|
_throttleLabel.Text = $"Throttle: {_throttleSmooth:F1} %";
|
|
}
|
|
|
|
public override void _Draw()
|
|
{
|
|
base._Draw();
|
|
}
|
|
|
|
private void SimulateStep(double dt)
|
|
{
|
|
_engine.Update(dt); // Engine uses _engine.Throttle inside its Update
|
|
|
|
if (EngineAudio != null)
|
|
{
|
|
EngineAudio.CurrentRPM = (float)_engine.RPM;
|
|
EngineAudio.CurrentThrottle = (float)_engine.ThrottlePosition;
|
|
EngineAudio.CurrentCombustionPower = (float)_engine.CombustionPower;
|
|
}
|
|
}
|
|
} |