diff --git a/Utilities/ProjectileUtils.cs b/Utilities/ProjectileUtils.cs index c7aed48b2b..b84b6418ee 100644 --- a/Utilities/ProjectileUtils.cs +++ b/Utilities/ProjectileUtils.cs @@ -42,6 +42,56 @@ namespace CalamityMod return null; } + // NOTE - Do not under any circumstance use these predictive methods for enemies or bosses. It is intended for minions and player-created projectiles. + // Due to its extremely precise nature, it will have little openings that allow players to react without dashing through the enemy. + // The results will be neither fun nor fair. + + /// + /// Calculates a velocity that approximately predicts where some target will be in the future based on Euler's Method. + /// + /// The starting position from where the movement is calculated. + /// The position of the target to hit. + /// The velocity of the target to hit. + /// The speed of the predictive velocity. + /// The number of iterations to perform. The more iterations, the more precise the results are. + public static Vector2 CalculatePredictiveAimToTarget(Vector2 startingPosition, Vector2 targetPosition, Vector2 targetVelocity, float shootSpeed, int iterations = 4) + { + float previousTimeToReachDestination = 0f; + Vector2 currentTargetPosition = targetPosition; + for (int i = 0; i < iterations; i++) + { + float timeToReachDestination = Vector2.Distance(startingPosition, currentTargetPosition) / shootSpeed; + currentTargetPosition += targetVelocity * (timeToReachDestination - previousTimeToReachDestination); + previousTimeToReachDestination = timeToReachDestination; + } + return (currentTargetPosition - startingPosition).SafeNormalize(Vector2.UnitY) * shootSpeed; + } + + /// + /// Calculates a velocity that approximately predicts where some target will be in the future based on Euler's Method. + /// + /// The starting position from where the movement is calculated. + /// The target to hit. + /// The speed of the predictive velocity. + /// The number of iterations to perform. The more iterations, the more precise the results are. + public static Vector2 CalculatePredictiveAimToTarget(Vector2 startingPosition, Entity target, float shootSpeed, int iterations = 4) + { + return CalculatePredictiveAimToTarget(startingPosition, target.Center, target.velocity, shootSpeed, iterations); + } + + /// + /// Makes a projectile home in such a way that it attempts to fractionally move towards a target's expected future position. + /// This is based on the results of the method. + /// + /// The projectile that should home. + /// The target. + /// The inertia of the movement change. + public static Vector2 SuperhomeTowardsTarget(this Projectile projectile, NPC target, float homingSpeed, float inertia) + { + Vector2 idealVelocity = CalculatePredictiveAimToTarget(projectile.Center, target, homingSpeed); + return (projectile.velocity * (inertia - 1f) + idealVelocity) / inertia; + } + public static void KillAllHostileProjectiles() { for (int x = 0; x < Main.maxProjectiles; x++)