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

        // 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?

  • 3
    \$\begingroup\$ It looks as though you've fixed the launch angle. For a parabolic arc, launch angle and speed are coupled. For a particular angle, there's exactly one speed that will hit the target. If you adjust the speed without adjusting the angle, you will miss. If varying speed is important to you, I'd recommend fixing the speed as an input, and computing (one of up to two possibilities for) the angle as an outcome. There's an example of doing this in both cases 2D & 3D in this answer \$\endgroup\$
    – DMGregory
    Feb 11, 2020 at 11:44
  • \$\begingroup\$ @DMGregory You're amazing!!!, Thank you so much \$\endgroup\$
    – Falyoun
    Feb 11, 2020 at 14:17


You must log in to answer this question.

Browse other questions tagged .