Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct here to familiarize yourself with the rules and how to post constructively.

  2. Unity 2022.1 is now available as the latest Tech release.
    Dismiss Notice
  3. Improve your project's performance with our new guide on profiling in Unity.
    Dismiss Notice

Angle required to hit a coordinate (x, y, z)

Discussion in 'Physics' started by dreamer-, Apr 23, 2018.

  1. dreamer-

    dreamer-

    Joined:
    Dec 9, 2016
    Posts:
    25
    I am trying to implement the mechanism shown in the below video


    The player can set the velocity of the ball and where it will land on the pitch(Watch the video for 10 s). I am trying to find the angle(rotation along the X axis) at which the ball has to be thrown to reach the selected point.

    The same question has been asked here
    https://stackoverflow.com/questions...projection-in-3d-for-an-object-to-step-at-giv
    But using the method suggested there
    (based on "Angle required to hit coordinate" https://en.wikipedia.org/wiki/Projectile_motion)
    I am not getting correct results.

    The code that I have currently have is given below.
    Code (CSharp):
    1.  
    2. private void LaunchBall()
    3. {
    4.     float angle = CalculateLaunchAngle(source, destination, velocity);
    5.     rb.velocity = Quaternion.Euler(angle, 0f, 0f) * direction * velocity;
    6. }
    7.  
    8. private float CalculateLaunchAngle(Vector3 source, Vector3 destination, float velocity)
    9.     {
    10.         float y = Mathf.Abs(destination.y - source.y);
    11.         float xx = destination.x - source.x;
    12.         float zz = destination.z - source.z;
    13.         float xz = Mathf.Sqrt(xx * xx + zz * zz);
    14.         float g = Physics.gravity.y;
    15.         float v = velocity;
    16.  
    17.         float sqrt = Mathf.Sqrt((v * v * v * v) - g * ((g * xz * xz) + (2 * y * v * v)));
    18.         if (float.IsNaN(sqrt))
    19.             return 0f;
    20.  
    21.         float angle1 = Mathf.Rad2Deg * Mathf.Atan(((v * v) + sqrt) / (g * xz));
    22.         float angle2 = Mathf.Rad2Deg * Mathf.Atan(((v * v) - sqrt) / (g * xz));
    23.  
    24.         Debug.Log("Angle 1 = " + angle1);
    25.         Debug.Log("Angle 2 = " + angle2);
    26.  
    27.         return angle1;
    28.     }
    29.  
    Please suggest a way forward.
     
unityunity