MrBot.Net/MRBot/Navigation/MrNavigation.cs
2023-12-08 15:20:12 -06:00

89 lines
2.5 KiB
C#

using System;
using LavishScriptAPI;
using Microsoft.Extensions.Logging;
using MRBot.IsxEq2;
using StackExchange.Profiling;
namespace MRBot.Navigation;
internal class MrNavigation
{
private const string AutoRunKey = "num lock";
private readonly ILogger<MrNavigation> _logger;
private readonly MiniProfiler _profiler;
public MrNavigation(ILogger<MrNavigation> logger, MiniProfiler profiler)
{
_logger = logger;
//_profiler = profiler;
}
private float AngleTo(double startingX, double startingZ, double targetX, double targetZ)
{
var deltaX = startingX - targetX;
var deltaZ = startingZ - targetZ;
// Calculate the angle in radians using Math.Atan2
double angleRad;
// using (_profiler.Step("MrNavigation.AngleTo.Math.Atan2"))
{
angleRad = Math.Atan2(deltaX, deltaZ);
}
// Convert radians to degrees
float angleDegrees;
// using (_profiler.Step("MrNavigation.AngleTo.ConvertRadiansToDegrees"))
{
angleDegrees = (float)(angleRad * (180.0 / Math.PI));
}
// using (_profiler.Step("MrNavigation.AngleTo.EnsureAngleIsInRange"))
{
// Ensure the angle is in the range [0, 360)
if (angleDegrees < 0) angleDegrees += 360;
}
return angleDegrees;
}
public void RunTowardsPoint(double targetX, double targetZ)
{
// using (_profiler.Step("MrNavigation.RunTowardsPoint"))
{
float angle;
// using (_profiler.Step("MrNavigation.RunTowardsPoint.AngleTo"))
{
angle = AngleTo(Extension.Me.Loc.X, Extension.Me.Loc.Z, targetX, targetZ);
}
// using (_profiler.Step("MrNavigation.RunTowardsPoint.Face"))
{
Extension.Me.Face(angle);
}
}
// using (_profiler.Step("MrNavigation.RunTowardsPoint.CheckIfMoving"))
{
if (Extension.Me.IsMoving) return;
}
// using (_profiler.Step("Logging navigation start"))
{
_logger.LogInformation("Starting navigation to ({targetX}, {targetZ})", targetX, targetZ);
}
// using (_profiler.Step("MrNavigation.RunTowardsPoint.Start"))
{
LavishScript.ExecuteCommand($"press \"{AutoRunKey}\"");
}
}
public void Stop()
{
if (!Extension.Me.IsMoving) return;
_logger.LogInformation("Stopping navigation");
LavishScript.ExecuteCommand($"press \"{AutoRunKey}\"");
}
}