I am currently using this formula to fire a projectile in my game.
Credit to Stephan-B for this wonderful formula: https://forum.unity.com/threads/throw-an-object-along-a-parabola.158855/
private IEnumerator FireProjectile()
{
// Move projectile to the position of throwing object + add some offset if needed.
Projectile.position = transform.position + new Vector3(0, 0.0f, 0);
// Calculate distance to target
float target_Distance = Vector3.Distance(Projectile.position, Target.position);
// Calculate the velocity needed to throw the object to the target at specified angle.
float projectile_Velocity = target_Distance / (Mathf.Sin(2 * FiringAngle * Mathf.Deg2Rad) / Gravity);
// Extract the X Y componenent of the velocity
float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(FiringAngle * Mathf.Deg2Rad);
float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin(FiringAngle * Mathf.Deg2Rad);
// Calculate flight time.
float flightDuration = target_Distance / Vx;
// Rotate projectile to face the target.
Projectile.rotation = Quaternion.LookRotation(Target.position - Projectile.position);
float elapse_time = 0;
while (elapse_time < flightDuration)
{
Projectile.Translate(0, (Vy - (Gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);
elapse_time += Time.deltaTime;
yield return null;
}
}
This works great, however, I don't want the projectile to rotate it's transform. I'd like it to keep it's rotation while it travels. I thought it would be as simple as commenting out this line:
// Rotate projectile to face the target.
Projectile.rotation = Quaternion.LookRotation(Target.position - Projectile.position);
But, doing this ruins the code and causes the projectile to go in the wrong direction. I also tried keeping the code the same and adding a billboard to the projectile, but doing so also causes the projectile to move in the wrong direction.
It appears that this formula relies on the projectile rotating to hit its target correctly. I like this formula because it let's me easily change the projectile's angle and the gravity affecting it, but I really need the projectile to keep its rotation throughout. Is anyone able to please assist me with this? Thanks so much!