# How can I launch a GameObject at a target if I am given everything except for its launch angle?

I have been working on this one for a few weeks, and I have yet to succeed. I have searched every resource out there, and tried them all, but still without success, so I do not believe existing links will be of much use to me at this point. I have purchased scripts from the Asset Store in hopes of finding some usable code there, but no such luck.

I am trying to launch an object at a target, given its position, its target position, the launch force, and the gravity. I am following this formula:

I have simplified the code to the best of my ability, but I still cannot consistently hit the target. (I am not actually launching the origin itself, but it seemed simpler than having code instantiating another GameObject.)

Does anyone know what I am doing wrong?

``````using UnityEngine;

public class Launcher : MonoBehaviour
{
public float speed = 10.0f;

void Start()
{
Launch(GameObject.Find("Target").transform);
}

public void Launch(Transform target)
{
float angle = GetAngle(transform.position, target.position, speed, -Physics2D.gravity.y);
var forceToAdd = new Vector2(Mathf.Cos(angle), Mathf.Sin(angle));
}

private float GetAngle(Vector2 origin, Vector2 destination, float force, float gravity)
{
float angle = 0.0f;

//Labeling variables to match formula
float x = Mathf.Abs(destination.x - origin.x);
float y = Mathf.Abs(destination.y - origin.y);
float v = force;
float g = gravity;

//Formula seen above
float valueToBeSquareRooted = Mathf.Pow(v, 4) - g * (g * Mathf.Pow(x, 2) + 2 * y * Mathf.Pow(v, 2));
if (valueToBeSquareRooted >= 0)
{
angle = Mathf.Atan(Mathf.Deg2Rad * (Mathf.Pow(v, 2) + Mathf.Sqrt(valueToBeSquareRooted)) / g * x);
}
else
{
//Destination is out of range
}

return angle;
}
}
``````

Again, I have spent weeks on this problem. I am at the end of my mental rope. Please help!

I previously posted my general formulas for 3-dimensional trajectory, but it should translate quite easily to 2-dimensional, since it effectively just sets an axis difference to zero:

Edit: I specifically handle removing each of TimeToDestination, LaunchSpeed, and LauchAngle. As a result, you can utilize either of the first two to reach a destination accurately (or, perfectly with time or as close as possible for speed or angle).

Calculating based on any of those criteria cannot reasonably be combined with any other, as:

Time is dependent primarily on horizontal speed (which means a hard-set speed requirement modified by an angle to hit the destination point, adding vertical speed to the launch)

Speed can fall short of the destination when too little force is applied. Then, any sped beyond the minimum required (at a 45 degree angle) can be added either to reach the destination at a low angle or a high angle.

Angle can always reach the destination, provided the angle of the launch is not less than the angle to the destination.

Edit again: Typos corrected.