Distance in a Trajectory of a projectile

Hello,

I am trying to implement the below formula.

Distance

In the equations on this page, the following variables will be used:
g: the gravitational acceleration—usually taken to be 9.81 m/s2 near the Earth’s surface
θ: the angle at which the projectile is launched
v: the velocity at which the projectile is launched
y0: the initial height of the projectile
d: the total horizontal distance traveled by the projectile

Code:

I scripted that formula as

distance = (((cannonScript.velocity*Mathf.Cos(cannonScript.angle))/gravity)*(cannonScript.velocity*Mathf.Sin(cannonScript.angle))+(Mathf.Sqrt(Mathf.Pow(cannonScript.velocity*Mathf.Sin(cannonScript.angle),2)+(2*gravity*ini_height))));

Code Explanation:

I have just parsed the formula using a machine readable, Javascript. I have used Mathf functions from the engine. I have double checked for the closing and opening braces.
I have done O/P the result, distance in the console window. The angle is degrees and I think I just receive it as a float value and pass it. I hope it is degrees in the right way. The initial height is 0 and gravity is 9.81.

GameObjects:

I have placed this script on a turret model from which the cannon prefab is launched every time.

Problem:

I get even negative values in the console window. For example if the angle is 31 and velocity is 11 my value (distance) is -0.1142434. I think it makes no sense.

I/P Variables:

My usage of angle and initial velocity are given by the following script.

http://codepad.org/bTUVFdc3

I am using the same angle and velocity.

Request:

My humble request is could someone help me in this. I have been working & not sure where I am wrong. I do also believe that all the values I have given as an input correspond to their respective real world values (metrics).

THANK you in advance

How about this- try expanding that out into about 5 lines to see everything more clearly, and then make it one line again when it’s all working properly. While it’s shorter in code to compress mathematical functions that way, it’s way harder to troubleshoot!

A few things to look out for- Mathf.Sin and Mathf.Cos take radians- use Mathf.Deg2Rad to fix the values before passing them into those functions.

So, an expanded version would go like this-

var vCosTheta : float = (cannonScript.velocity * Mathf.Cos(cannonScript.angle * Mathf.Deg2Rad));
var firstPart : float = vCosTheta / gravity;

var 2gyo : float = 2 * gravity * ini_height;
var vSinTheta : float = cannonScript.velocity * Mathf.Sin(cannonScript.angle * Mathf.Deg2Rad);
var bitsUnderRoot : float = Mathf.Pow(vSinTheta, 2) + 2gyo;
var secondPart : float = vSinTheta + Mathf.Sqrt(bitsUnderRoot);

var result : float = firstPart * secondPart;

distance = result;