implementing projectiles - angle of impact
hey guys,
Im implementing a long range artillery mechanic in my game. It is to be relatively realistic and for this, Ive been basing most of what Ive been doing on these links:
[https://www.forrestthewoods.com/blog/solving_ballistic_trajectories/] [https://vilbeyli.github.io/Projectile-Motion-Tutorial-for-Arrows-and-Missiles-in-Unity3D/] [https://en.wikipedia.org/wiki/Projectile_motion]
Ive implemented the "Angle θ required to hit coordinate (x, y)" part of these calcs.
Ive gotten it working well enough and it works quite well - except the projectiles are not hitting the mark - they are barely missing consistently and exactly.
Heres the code for the angle calculation:
public float CalcAngle(Transform mark, Transform shellSpawn)
{
Vector3 diff = mark.transform.position - shellSpawn.transform.position;
float distH = diff.y;
//float distH = 0;
Debug.Log(distH);
float distL = Vector3.Distance(shellSpawn.transform.position, mark.transform.position);
float v = _ShellVelocityMS;
float g = Physics.gravity.y;
float x = distL;
float y = distH;
float v2 = v * v;
float v4 = v * v * v * v;
float gx2 = g * x * x;
float yv2 = 2 * y * v * v;
float gx = g * x;
float res = Mathf.Sqrt(v4 - g * (gx2 + yv2));
float resFlat = (v2 - res) / gx;
float resHigh = (v2 + res) / gx;
resFlat = Mathf.Atan(resFlat) * Mathf.Rad2Deg;
resHigh = Mathf.Atan(resHigh) * Mathf.Rad2Deg;
float angle = resFlat;
if (float.IsNaN(angle))
angle = _IdleAngle * -1;
diff = diff.normalized;
diff = (diff * Mathf.Cos(angle) * v) + (Vector3.up * Mathf.Sin(angle) * v);
//Debug.Log(diff);
return angle;
}
I have two cannons - both shooting at different elevations: cannon1 launches at 2 meters height cannon2 launches at 1 meter height
at flat trajectories, cannon 1 overshoots massively, cannon 2 half as much. At a high trajectory, they still overshoot - not at the same level, but they stay in relative relation to each other.
Setting distH from a positive to a negative value pulls the landing sites of the shots closer to the cannons, as expected - but the same discrepancy is still to be had. Something is not implemented correctly in my calculations and Im stumped .... would be great if yall could throw a look over it.
Answer by Seranach · Jan 07 at 09:59 PM
Also, ignore the [diff] variable at the end, was the rest of something I was working on.
update:
instead of using my code, I straight-up copied the code from [https://github.com/forrestthewoods/lib_fts/blob/master/code/fts_ballistic_trajectory.cs] namely the function at 285 (which is the code for this article [https://www.forrestthewoods.com/blog/solving_ballistic_trajectories/]) which shows the code in-action doing precisely what I need.
aaaand im getting exactly the same result as with my code .... which is absolutely insane. Im literally using a function that is proven to be correct - and im getting an incorrect outcome.
If i ever find out what is buggering here, ill give an update, of course