- Home /
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.
Comment