How to shoot objects in movement?

111 Views Asked by At

See my image below:

enter image description here

The black-right-arrow is my ship and the red circle my enemy (radius 1.2). Both are in movement without acceleration. I need kill the red circle with precision, what type of calculations can I use with only linear velocity, position, and radius data?

Note: The bullet has 0.5s of lifetime and the speed 40 and radius 0.2

I'm trying to implement this in C#.

public static Vector3 CalculatePreciseShootDirection(Vector3 shipPosition, Vector3 shipVelocity,
                                                         Vector3 targetPosition, Vector3 targetVelocity,
                                                         float bulletLifetime, float bulletSpeed)
        {
            Vector3 shipFuturePosition = shipPosition + bulletLifetime * shipVelocity;
            Vector3 targetFuturePosition = targetPosition + bulletLifetime * targetVelocity;
            Vector3 relativeDisplacement = targetFuturePosition - shipFuturePosition;
            float timeToTarget = Vector3Magnitude(relativeDisplacement) / bulletSpeed;
            Vector3 adjustedTargetPosition = targetPosition + timeToTarget * targetVelocity;
            Vector3 shootingDirection = adjustedTargetPosition - shipPosition;
            float shootingDistance = Vector3Magnitude(shootingDirection);
            float maxDistance = bulletLifetime * bulletSpeed;
            if (shootingDistance <= maxDistance)
            {
                return Vector3.Normalize(shootingDirection);
            }
            else
            {
                return Vector3.Zero;
            }
        }
        
        private static float Vector3Magnitude(Vector3 v)
        {
            return (float)Math.Sqrt(v.X * v.X + v.Y * v.Y + v.Z * v.Z);
        }
1

There are 1 best solutions below

1
Ibraheem Khazbak On

You need to add both velocities together and set that as the initial speed of the projectile.

like so:

projectile speed = (X= V1.x+V2.x, Y= V1.y+V2.y)