How to do it...

Thanks to our previous hard work, this recipe is a real piece of cake:

  1. Create the GetFireDirection function:
public static Vector3 GetFireDirection (Vector3 startPos, Vector3 endPos, float speed) 
{ 
    // body 
}
  1. Solve the corresponding quadratic equation:
Vector3 direction = Vector3.zero; 
Vector3 delta = endPos - startPos; 
float a = Vector3.Dot(Physics.gravity, Physics.gravity); 
float b = -4 * (Vector3.Dot(Physics.gravity, delta) + speed * speed); 
float c = 4 * Vector3.Dot(delta, delta); 
if (4 * a * c > b * b) 
    return direction; 
float time0 = Mathf.Sqrt((-b + Mathf.Sqrt(b * b - 4 * a * c)) / (2*a)); 
float time1 = Mathf.Sqrt((-b - Mathf.Sqrt(b * b - 4 * a * c)) / (2*a)); 
  1. If shooting the projectile is feasible given the parameters, ...

Get Unity 2018 Artificial Intelligence Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.