Cannon fires straight upward

I’m trying to simulate a cannon for my game.

It’s given a target Vector, where the cannon ball should be fired at. I want a realistic calaculation of the trajectory path, the formula is included in the script.

At the moment, I have not found a solution for the occuring problem; the cannonball lifts straight up (90°) and falls down after a period of time (on the same spot = “Exit”.position). The cannonball is a rigibody which is assigned to the cannon. Here’s the script for the logic:

     protected override void Update()
        {
          if (Input.GetKeyDown("q"))
            {
                if (canFire) FireCannon();
                else canFire = true;
            }
    }
       private void FireCannon()
    {

        Vector3 pos = transform.FindChild("Exit").position;
        float dist = Vector3.Distance(pos, target);
               
        float Vi = Mathf.Sqrt(dist * -Physics.gravity.y / (Mathf.Sin(Mathf.Deg2Rad * angle * 2)));
        float Vy, Vz;

        Vy = Vi * Mathf.Sin(Mathf.Deg2Rad * angle);
        Vz = Vi * Mathf.Cos(Mathf.Deg2Rad * angle);
       
        Vector3 localVelocity = new Vector3(0f, Vy, Vz);
        Vector3 globalVelocity = transform.TransformVector(localVelocity);
       
        Rigidbody clone = Instantiate(projektil, pos, transform.rotation) as Rigidbody;
        clone.AddForce(globalVelocity * 1000);
       
        canFire = false;   
    }

I have worked quite long to find an error but this was without a result. I hope you can help me here.

On lines 18 and 19 you are using Sin/Cos to compute the axis speeds based on the “angle” value.

On line 22 you are using the local object transform to modify the localVelocity vector again.

I don’t think you want to be doing this, although perhaps you do. I’m not sure.

The default Unity camera setup has Y going up, X going right and Z going away.

You can temporarily insert code at line 23 a test line to see which way things are going:

// this should make the shot go to the right:
globalVelocity = new Vector3( 1, 0, 0);

or also:

// this should make the shot go up and to the right:
globalVelocity = new Vector3( 1, 1, 0);

Hi, using your code causes the projectile to simply drop to the ground.

Edit; sorry for the lack of info; haven’t slept for nearly 2 days, hope I can provide better data tomorrow