# Predicting hit coordinates of a moving object

I’ve found myself experimenting with a challenging idea, and would appreciate some help.

Lets say I have a small pirate game, 2 ships have cannons and are moving. I’m trying to have the ships determine (predict) the coordinates to which they fire their cannons so that they collide with the other moving ship.

I cannot use the usual Raycast as it will shoot at the CURRENT coordinates of the enemy ship, not the predicted one.

I have shamelessly stolen this code from @peterho0218 on this thread: Click Me

``````private Vector3 predictedPosition(Vector3 targetPosition, Vector3 shooterPosition, Vector3 targetVelocity, float projectileSpeed)
{
Vector3 displacement = targetPosition - shooterPosition;
float targetMoveAngle = Vector3.Angle(-displacement, targetVelocity) * Mathf.Deg2Rad;

//if the target is stopping or if it is impossible for the projectile to catch up with the target (Sine Formula)
if (targetVelocity.magnitude == 0 || targetVelocity.magnitude > projectileSpeed && Mathf.Sin(targetMoveAngle) / projectileSpeed > Mathf.Cos(targetMoveAngle) / targetVelocity.magnitude)
{
Debug.Log("Position prediction is not feasible.");
return targetPosition;
}

//also Sine Formula
float shootAngle = Mathf.Asin(Mathf.Sin(targetMoveAngle) * targetVelocity.magnitude / projectileSpeed);
return targetPosition + targetVelocity * displacement.magnitude / Mathf.Sin(Mathf.PI - targetMoveAngle - shootAngle) * Mathf.Sin(shootAngle) / targetVelocity.magnitude;
}
``````

Just spitballing here: I’d start with the variables,

• the distance between boats
• target boat velocity
• cannon travel time

You can then use those variables to create a box collider that leads the target boat with an offset in the direction of movement that adjusts its offset based on the target boats velocity, and the distance between the target boat and the firing boat.

Then you can have the canons raycast out and when they hit that collider and fire, their cannonballs should hit the ship if its speed / direction / distance hasn’t changed that much (and you’ve done your math right!).

But I’m sure there are a billion ways to do it