# How do i predict the position of my player for the turret to shoot at?

I have a turret and a player spaceship. this turret shoots at the player within a certain range but, as the player fliest around, every shot misses. can any of you possibly help me establish a mathmatical formula to calculate this?

what values do i need to put where etc. any help is greatly appriciated, i have been breaking my head over this for the last few days

We can simply solve this by using Sine Formula.

For the method in Unity:

``````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;
}
``````

You may call it in Update() method to use it.

i finally got it right only a little while before your comment!
i ended up doing this:
(i happened to know the speed of my bullet never changes)

``````//get player position
Vector3 playerPos = turretRange[0].transform.position;
//get bullet speed
float bulletSpeed = 600f * Time.fixedDeltaTime;
//calculate distance to player with pythagoras
float playerDistance = Vector3.Distance(transform.position, playerPos);
//calculate traveltime
travelTime = playerDistance / bulletSpeed;
predictedPosition = playerPos + playerData.movementVector * travelTime;
``````

thanks a lot anyway!