I am trying to make the AI shoot an arrow and always hit the target. Assuming that the target is within his range I am stuck what the correct way is to do this. I search and found some solutions but they do not seem to work 100% perfectly in my code (How can I shoot an arrow if I know the shot power and target?).
My code is (target
is the prefab I want the AI to hit):
arrow.GetComponent<Rigidbody>().AddForce (Aim()*speed, ForceMode.VelocityChange);
private Vector3 Aim()
{
float xAim = target.transform.position.x - transform.position.x;
float yAim = Mathf.Rad2Deg * Mathf.Atan((speed*speed + Mathf.Sqrt(speed*speed*speed*speed) - (-Physics.gravity.y) * (-Physics.gravity.y * HorizontalDistance()*HorizontalDistance()) + 2 * VerticalDistance() * speed*speed / -Physics.gravity.y * HorizontalDistance()));
float zAim = target.transform.position.z - transform.position.z;
Vector3 aim = new Vector3(xAim, yAim, zAim).normalized;
return aim;
}
private float HorizontalDistance()
{
float xDistance = target.transform.position.x - transform.position.x;
// float zDistance = target.transform.position.z - transform.position.z;
float distance = Mathf.Sqrt(xDistance*xDistance);// + (zDistance*zDistance));
return distance;
}
private float VerticalDistance()
{
return Mathf.Abs(target.transform.position.y - transform.position.y);
}
Mathf.Sqrt(speed*speed*speed*speed)
which will always be equal tospeed*speed
. Try assembling the equation step by step, not on one line - it should help. \$\endgroup\$