I’m working on a simple script where a projectile is given an initial velocity to hit a target.
I’m plugging in the target and the initial angle for the projectile.
I used an equation that solves for initial velocity and given angle. Unfortunately it is not working as expected and I’m not sure why. Here is the equation that I used.
(if image won’t show, here is the link to it )
And here is the code. I broke it down as much as I could for clarity.
public float tilt;
float g;
Rigidbody rb;
public GameObject target;
void Start()
{
rb = transform.GetComponent<Rigidbody>();
g = 9.8f;
}
void Update()
{
if (Input.GetMouseButtonDown(0)) {
rb.velocity = CalcVelocity(target.transform.position);
}
}
Vector3 CalcVelocity(Vector3 pos1)
{
transform.position = Vector3.zero;
float sine, cosine;
sine = Mathf.Sin(tilt * Mathf.Deg2Rad);
cosine = Mathf.Cos(tilt * Mathf.Deg2Rad);
float velocity;
float numerator, denominator;
Vector3 force;
numerator = Mathf.Pow(pos1.z, 2) * 9.8f;
denominator = 2 * pos1.z * sine - 2 * pos1.y * Mathf.Pow(cosine,2);
print(numerator);
print(denominator);
velocity = Mathf.Sqrt(f:numerator / denominator);
force = new Vector3(0.0f,sine,cosine)* velocity;
return force;
}