I have two points: A launch point, and a target. I have a script that calculates the force i need to apply to my object, so it lands on my target.
[Formula] (http://i.ajdesigner.com/projectilemotion/range_equation_initial_velocity.png) where v0 is initial velocity, R is the range, g is the acceleration of gravity, and θ is the angle.
This works fine, but only if the y-axis of my launch point and target are the same. How can i calculate the force i need, but also being able to hit my target, even if it is above or below me.
Code:`using UnityEngine;
using System.Collections;
public class LobbTest : MonoBehaviour {
public int roundTo;
public Transform target;
private Rigidbody rb;
private float range;
private float gravity;
private float angle;
private float velocity;
private float angleRad;
public void Lobb ()
{
rb = GetComponent<Rigidbody> ();
range = target.position.x - transform.position.x;
Debug.Log ("range = " + range);
gravity = -Physics.gravity.y;
Debug.Log ("gravity = " + gravity);
angle = transform.eulerAngles.z;
Debug.Log ("angle = " + angle);
velocity = (Mathf.Sqrt ((range * gravity) / CalculateSine(angle, 2)));
Debug.Log ("velocty = " + velocity);
rb.velocity = transform.right * velocity;
}
float CalculateSine(float angle, float multiplier)
{
float radAngle = angle * Mathf.PI / 180f;
float radSine = Mathf.Sin (multiplier * radAngle);
radSine = Round (radSine, roundTo);
return radSine;
}
float Round(float f, int roundTo)
{
return Mathf.Round (f * Mathf.Pow(10, roundTo)) / Mathf.Pow(10, roundTo);
}`
}