added projectile targeting anticipation
This commit is contained in:
parent
eea6830534
commit
7846f1a068
3 changed files with 68 additions and 24 deletions
|
|
@ -1,3 +1,5 @@
|
|||
using System;
|
||||
|
||||
namespace Dancer;
|
||||
|
||||
public static class Physics
|
||||
|
|
@ -15,6 +17,49 @@ public static class Physics
|
|||
{
|
||||
return 0.5f * fluidMassDensity * area * dragCoefficient;
|
||||
}
|
||||
|
||||
public static AnticipationResult? AnticipateProjectile(
|
||||
Vector2 projectilePosition,
|
||||
float projectileSpeed,
|
||||
Vector2 targetPosition,
|
||||
Vector2 targetVelocity
|
||||
)
|
||||
{
|
||||
var difference = targetPosition - projectilePosition;
|
||||
var distanceSquared = difference.LengthSquared();
|
||||
if (distanceSquared < 0.001) return new(0, targetPosition);
|
||||
var radialVelocitySquared = difference.Dot(targetVelocity);
|
||||
var projectileSpeedSquared = projectileSpeed * projectileSpeed;
|
||||
var targetSpeedSquared = targetVelocity.LengthSquared();
|
||||
var a = targetSpeedSquared - projectileSpeedSquared;
|
||||
|
||||
float t;
|
||||
if (Mathf.Abs(a) < 0.001)
|
||||
{
|
||||
t = -distanceSquared / (2 * radialVelocitySquared);
|
||||
}
|
||||
else
|
||||
{
|
||||
var discriminant = radialVelocitySquared * radialVelocitySquared - a * distanceSquared;
|
||||
if (discriminant < 0) return null;
|
||||
|
||||
var t0 = (-radialVelocitySquared + Mathf.Sqrt(discriminant)) / a;
|
||||
var t1 = (-radialVelocitySquared - Mathf.Sqrt(discriminant)) / a;
|
||||
t = (t0, t1) switch
|
||||
{
|
||||
(< 0f, _) => t1,
|
||||
(_, < 0f) => t0,
|
||||
_ => Mathf.Min(t0, t1),
|
||||
};
|
||||
}
|
||||
|
||||
if (t < 0f) return null;
|
||||
return new(t, TargetPositionAt(t));
|
||||
|
||||
Vector2 TargetPositionAt(float time) => targetPosition + targetVelocity * time;
|
||||
}
|
||||
|
||||
public sealed record AnticipationResult(float Time, Vector2 Position);
|
||||
}
|
||||
|
||||
public static class Extensions
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue