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.