AddForce in wrong direction

I want to shoot a projectile following a calculated trajectory.

Unfortunately, the projectile moves in the wrong direction but lands after the correct distance. Currently, it fires 90 degree to the left.
The prefab in instanciated on an object called “exit” which is completely zeroed out and pints in the direction of the cannon.
If I place my cannon exactly next to the target on the right hand site, it hits the target. But only in this case.

this is my code for the method:

 public void FireTest()
    {
        if(distance > maxRangeDirect)
        {
            Debug.Log("Ziel außer Reichweite");
            return;
        }

        transform.LookAt(targetPos);
        //exit.LookAt(target.transform);
        float deltaX = (targetPos.x - exitPos.x);
        float deltaY = (targetPos.y - exitPos.y);
        float vMax = velocity;
        float g = 9.8f;

        Debug.Log("X: " + deltaX + " Y: " + deltaY);
        float b = vMax * vMax - deltaY * g;
        float discriminant = b * b - g * g * (deltaX * deltaX + deltaY * deltaY);
        float discRoot = Mathf.Sqrt(discriminant);

        Debug.Log("B: " + b + " discroot: " + discRoot);
        if (discriminant < 0) Debug.Log("Error: "+ discriminant);
        float T_min = Mathf.Sqrt((b - discRoot) * 2 / (g * g));
       
        float T_max = Mathf.Sqrt((b + discRoot) * 2 / (g * g));

        Debug.Log("Min: " + T_min + " Max: " + T_max);
        float T_avg = (T_min);
        float vx = deltaX / T_avg;
        float vy = deltaY / T_avg + T_avg * g / 2;
               
        Vector3 vel = new Vector3(vx , vy, Vector3.forward.z);
        Debug.Log("Vel: "+vel);

        GameObject shot = Instantiate(roundPrefab, exitPos, Quaternion.identity);
       
        shot.GetComponentInChildren<Rigidbody>().AddForce(vel, ForceMode.VelocityChange);
    }

If someone has an Idea pleas let me know, I’m working way too long on this.

Some of your code goes a little over my head but Ill take a stab at it.

Is it something to do with your velocity taking its forward vector from world space and not using the forward vector of the shot? From a skim through your code it would seem your Z component will always == 1.

If I were building a cannon, I would use my right vector to control pitch, up vector to control rotation and forward vector to control how far my shot went.

Apologies if Im completely off, like i say i dont completely understand the code. Just looking for something you might have overlooked.

Hi, I guess that’s the problem, but it should theoretically work with x/y only, as it’s technically 2d space after the cannon trunts to the target