title: Unity - Projectile Motion, find the angle needed to hit coordinates x,y
body: <p>Plenty of questions asked around the same topic, but nothing seems to be working for me. </p>
  
  <p>The problem is simple, a player and an enemy are on the x,y plane. I want to launch my projectile at a calculated angle in such way that the projectile will hit the enemy at it's coordinates.</p>
  
  <p>I've tried implementing both</p>
  
  <p><a href="https://en.wikipedia.org/wiki/Projectile_motion#Angle_of_reach" rel="nofollow noreferrer">Angle of Reach</a> and <a href="https://en.wikipedia.org/wiki/Projectile_motion#Angle_%7F&#39;%22%60UNIQ--postMath-0000003A-QINU%60%22&#39;%7F_required_to_hit_coordinate_(x,y)" rel="nofollow noreferrer">Angle required to hit x,y</a></p>
  
  <p>Both of these implementation end up doing the same for me; <a href="https://i.stack.imgur.com/57PTc.png" rel="nofollow noreferrer">Shooting but not hitting the target in this manner</a></p>
  
  <p>Any help or pointers would be much appreciated! Thank you</p>
  
  <p>Here is the code:</p>
  
  <pre><code>public Rigidbody projectile;
  public float projectileSpeed;
  public float Firerate = 9f;
  private float nextfire;
  
  private GameObject enemy;
  private float gravity = Physics.gravity.y;
  private Vector3 directionalVector;
  
  // Start is called before the first frame update
  void Start()
  {
      enemy = GameObject.FindGameObjectWithTag("enemy");
  
  }
  
  
  void Update()
  {
      directionalVector = enemy.transform.position - transform.position;
  
  }
  void FixedUpdate()
  {
  
      nextfire = Time.time + (1 / Firerate);
  
      float projectileSpeed2 = projectileSpeed * projectileSpeed;
      float projectileSpeed4 = projectileSpeed2 * projectileSpeed2;
      float x = enemy.transform.position.x;
      float y = enemy.transform.position.y;
      float x2 = x * x;
  
  
  
      float theta = Mathf.Atan(projectileSpeed2-Mathf.Sqrt(projectileSpeed4-gravity*(gravity*x2+2*y*projectileSpeed2))/gravity*x);
      print(theta);
  
      Vector3 releaseVector = (Quaternion.AngleAxis(theta, Vector3.up) * directionalVector).normalized;
  
      Debug.DrawRay(transform.position, releaseVector, Color.red,0.5f);
      Rigidbody instantiatedProjectile = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
      instantiatedProjectile.velocity = releaseVector * projectileSpeed;
  }
  </code></pre>
  
  <p>}</p>