I am working on a project where I am launching a projectile and according to the following snippet:
// launches the object towards the TargetObject with a given LaunchAngle
void Launch()
{
// think of it as top-down view of vectors:
// we don't care about the y-component(height) of the initial and target position.
Vector3 projectileXZPos = new Vector3(transform.position.x, 0.0f, transform.position.z);
Vector3 targetXZPos = new Vector3(TargetObjectTF.position.x, 0.0f, TargetObjectTF.position.z);
// rotate the object to face the target
transform.LookAt(targetXZPos);
// shorthands for the formula
float R = Vector3.Distance(projectileXZPos, targetXZPos);
float G = Physics.gravity.y;
float tanAlpha = Mathf.Tan(LaunchAngle * Mathf.Deg2Rad);
float H = (TargetObjectTF.position.y + GetPlatformOffset()) - transform.position.y;
// calculate the local space components of the velocity
// required to land the projectile on the target object
float Vz = Mathf.Sqrt(G * R * R / (2.0f * (H - R * tanAlpha)) );
float Vy = tanAlpha * Vz;
// create the velocity vector in local space and get it in global space
Vector3 localVelocity = new Vector3(0f, Vy, Vz);
Vector3 globalVelocity = transform.TransformDirection(localVelocity);
// launch the object by setting its initial velocity and flipping its state
rigid.velocity = globalVelocity;
bTargetReady = false;
}
Everything seems to work perfectly except:
1- Whenever I increase the velocity it gets beyond the target.
2- Whenever I decrease the velocity it does not reach the target.
So how am I able to increase the speed and reach the exact target?