I need help with some trajectory calculation math

I’m working on a simple script where a projectile is given an initial velocity to hit a target.
I’m plugging in the target and the initial angle for the projectile.
I used an equation that solves for initial velocity and given angle. Unfortunately it is not working as expected and I’m not sure why. Here is the equation that I used.

(if image won’t show, here is the link to it )

And here is the code. I broke it down as much as I could for clarity.

 public float tilt;
    float g;
    Rigidbody rb;
    public GameObject target;

    void Start()
    {
        rb = transform.GetComponent<Rigidbody>();
        g = 9.8f;
      
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {         

            rb.velocity = CalcVelocity(target.transform.position);         
        }
    }




    Vector3  CalcVelocity(Vector3 pos1)
    {
         transform.position = Vector3.zero;
     
        float sine, cosine;
        sine = Mathf.Sin(tilt * Mathf.Deg2Rad);
        cosine = Mathf.Cos(tilt * Mathf.Deg2Rad);
        float velocity;
        float numerator, denominator;
        Vector3 force;
        numerator = Mathf.Pow(pos1.z, 2) * 9.8f;     
        denominator = 2 * pos1.z * sine - 2 * pos1.y * Mathf.Pow(cosine,2);
        print(numerator);
        print(denominator);
        velocity = Mathf.Sqrt(f:numerator / denominator);
        force = new Vector3(0.0f,sine,cosine)* velocity;
        return force;
    }

Assuming the formula you’ve linked in the image is correct, you made an error in your implementation. It’s not

2 * pos1.z * Mathf.Sin(tilt * Mathf.Deg2Rad)

but

pos1.z * Mathf.Sin(2 * tilt * Mathf.Deg2Rad)

All this of course assumes that your projectiles starts at the world space origin (0,0,0) and the target object is located at the worldspace position (0,y,z)

Note by using the double angle identity you could keep your sine and cosine as you originally have calculated them and use this “denominator”:

denominator = (pos1.z*sine - pos1.y*cosine)*2*cosine;

ps:
Note that you should avoid using Mathf.Pow when just calculating the square. _Even though Mathf.Pow internally optimises integer powers, it’s generally a slow operation and doesn’t really help the readability. Also this: Mathf.Pow(pos1.z, 2) isn’t really shorter than this pos1.z * pos1.z (it’s actually 5 characters longer ^^)

1 Like

That was it! Goodness, I can waste hours just from overlooking stupid mistakes like that. Thank you for the fresh eyes and the optimization tips. Much appreciated!