I need someone to explain to me why the following is happening:
There is projectile launched along the arc, calculated with this piece of code:
Code
// Source: https://discussions.unity.com/t/740303
public static bool CalculateHighTrajectory(Vector3 start, Vector3 end, float muzzleVelocity, float gravity, out float angle)
{
Vector3 dir = end - start;
float vSqr = muzzleVelocity * muzzleVelocity;
float y = dir.y;
dir.y = 0.0f;
float x = dir.sqrMagnitude;
float uRoot = vSqr * vSqr - gravity * (gravity * (x) + (2.0f * y * vSqr));
if (uRoot < 0.0f)
{
// Target is out of range.
angle = -45.0f;
return false;
}
float r = Mathf.Sqrt(uRoot);
float bottom = gravity * Mathf.Sqrt(x);
angle = -(Mathf.Atan2(vSqr + r, bottom) * Mathf.Rad2Deg);
return true;
}
This works, however projectile is falling just tiny bit too short. After review, it looks like this is caused by integration and fact that gravity is applied first, what produces some kind of offset. To compensate this I added additional initial force equal to -gravity * delta
, but then projectile goes too far by exactly same amount, so instead I applied half of this force and now it works correctly.
You can see below orange sphere what is the target/landing position and two trails, left one with correction and second one without it.
My question is: why I need to apply only half of delta?
Also is it actually the correct way to fix this problem?