Files
ParkingRobot/Simulation/Core/SimulationClock.cs
T

39 lines
1.1 KiB
C#

using System.Diagnostics;
namespace MyParking.Simulation.Core;
/// <summary>
/// 以固定周期推进离线仿真世界。
/// </summary>
public sealed class SimulationClock(
SimulationWorld world,
ILogger<SimulationClock> logger) : BackgroundService
{
private static readonly TimeSpan TickInterval =
TimeSpan.FromMilliseconds(20);
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
logger.LogInformation(
"停车机器人离线仿真时钟已启动,周期{Period}ms。",
TickInterval.TotalMilliseconds);
using var timer = new PeriodicTimer(TickInterval);
var stopwatch = Stopwatch.StartNew();
var previousSeconds = stopwatch.Elapsed.TotalSeconds;
while (await timer.WaitForNextTickAsync(stoppingToken))
{
var currentSeconds = stopwatch.Elapsed.TotalSeconds;
var deltaTimeSeconds = Math.Clamp(
currentSeconds - previousSeconds,
0.001,
0.1);
previousSeconds = currentSeconds;
world.Step(deltaTimeSeconds);
}
}
}