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:

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;

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.

Also, ignore the

`````` variable at the end, was the rest of something I was working on.
``````

A lot of time since the original question, but in case anyone else needs an answer:
For me the problem was that Atan function apparently gives incorrect result (good job Unity), using
Atan2(v2 - res, gx), in terms above, fixed the issue.
Also in the code above, converting to degrees from radians is not needed, since Cos and Sin functions needed afterwards, accept values in radians.