3

How do I calculate the angle of a trajectory to hit the target, without knowing the velocity. I only know the max height, offset height and the distance to the target.

This is what I got so far (I don't know how to calculate offset height ):

 float GetAngle(Vector3 startLocation, Vector3 endLocation, float maxHeight)
 {
         float distance = Mathf.Sqrt(Mathf.Pow(startLocation.x - endLocation.x,2) + Mathf.Pow(startLocation.z - endLocation.z,2));

         float offsetHeight = endLocation.y - startLocation.y;
         //how do I calculate offset height in this equation ?
         return -Mathf.Atan (4 * maxHeight/ distance ) + Mathf.PI;
 }

I use this to calculate the velocity (works fine I only need the correct angle):

float LaunchVelocity (Vector3 startLocation, Vector3 endLocation, float angle)
 {
         float range = Mathf.Sqrt(Mathf.Pow(startLocation.x - endLocation.x,2) + Mathf.Pow(startLocation.z - endLocation.z,2));
         float offsetHeight = endLocation.y - startLocation.y;
         float gravity = Physics.gravity.y;

         float velocity = range * range * gravity;
         velocity /= range * Mathf.Sin(2 * angle) + 2 * offsetHeight * Mathf.Pow(Mathf.Cos(angle),2);
         return Mathf.Sqrt(velocity);
 }
1

1 Answer 1

4

I got the solution:

float GetAngle(float height, Vector3 startLocation, Vector3 endLocation)
    {
        float range = Mathf.Sqrt(Mathf.Pow(startLocation.x - endLocation.x,2) + Mathf.Pow(startLocation.z - endLocation.z,2));
        float offsetHeight = endLocation.y - startLocation.y;
        float g = -Physics.gravity.y;

        float verticalSpeed = Mathf.Sqrt(2 * gravity * height);
        float travelTime = Mathf.Sqrt(2 * (height - offsetHeight) / g) + Mathf.Sqrt(2 * height / g);
        float horizontalSpeed = range / TravelTime;
        float velocity = Mathf.Sqrt(Mathf.Pow(verticalSpeed,2) +  Mathf.Pow(horizontalSpeed, 2));

        return -Mathf.Atan2(verticalSpeed / velocity, horizontalSpeed / velocity) + Mathf.PI;
    }
1
  • Very nice. Don't forgot to accept it so other's know it is solved.
    – apxcode
    Nov 28, 2014 at 8:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.