For some reason I had this same script working in the same conditions before but now it’s not working in the same situation i have one projectile that just fires from the location of the entity shooting it. That works fine and is really accurate, but when a projectile is far away from the “Caster” it stops working and is like way behind the intended target. By exactly 4 meters everytime it misses by one in-game cell everytime.
//This is my aiming script
public static Vector3 Aimbot(Transform target, Vector3 startPos, float projectileSpeed)
{
Vector3 enemyPostion = target.transform.position;
Enemy enemy = target.GetComponent<Enemy>();
Vector3 enemyPosition = target.GetComponent<Collider>().bounds.center;
float distance = Vector3.Distance(startPos, enemyPosition);
float travelTime = distance / (projectileSpeed + (enemy.velocity.magnitude));
Vector3 predictedPosition = enemyPosition + (enemy.velocity * travelTime);
return predictedPosition;
}
//this is called when the projectile is created look at where I need to hit then move forward at a set speed.
void Start()
{
if(startVFX != null)
Instantiate(startVFX, transform.position, startVFX.transform.rotation);
if(GetComponent<Rigidbody>() == null)
{
Rigidbody rb = gameObject.AddComponent<Rigidbody>();
rb.constraints = RigidbodyConstraints.FreezeAll;
rb.useGravity = false;
}
transform.LookAt(DamageManager.Aimbot(target.transform, transform.position, speed));
}
//calculate the targets velocity per frame
IEnumerator CalcVelocity()
{
while(true)
{
yield return new WaitForSeconds(Time.deltaTime);
Vector3 currentPosition = transform.position;
velocity = (currentPosition - lastPosition) / Time.deltaTime;
lastPosition = currentPosition;
}
}