Plenty of questions asked around the same topic, but nothing seems to be working for me.
The problem is simple, a player and an enemy are on the x,y plane. I want to launch my projectile at a calculated angle in such way that the projectile will hit the enemy at it's coordinates.
I've tried implementing both
Angle of Reach and Angle required to hit x,y
Both of these implementation end up doing the same for me; Shooting but not hitting the target in this manner
Any help or pointers would be much appreciated! Thank you
Here is the code:
public Rigidbody projectile;
public float projectileSpeed;
public float Firerate = 9f;
private float nextfire;
private GameObject enemy;
private float gravity = Physics.gravity.y;
private Vector3 directionalVector;
// Start is called before the first frame update
void Start()
{
enemy = GameObject.FindGameObjectWithTag("enemy");
}
void Update()
{
directionalVector = enemy.transform.position - transform.position;
}
void FixedUpdate()
{
nextfire = Time.time + (1 / Firerate);
float projectileSpeed2 = projectileSpeed * projectileSpeed;
float projectileSpeed4 = projectileSpeed2 * projectileSpeed2;
float x = enemy.transform.position.x;
float y = enemy.transform.position.y;
float x2 = x * x;
float theta = Mathf.Atan(projectileSpeed2-Mathf.Sqrt(projectileSpeed4-gravity*(gravity*x2+2*y*projectileSpeed2))/gravity*x);
print(theta);
Vector3 releaseVector = (Quaternion.AngleAxis(theta, Vector3.up) * directionalVector).normalized;
Debug.DrawRay(transform.position, releaseVector, Color.red,0.5f);
Rigidbody instantiatedProjectile = Instantiate(projectile, transform.position, transform.rotation) as Rigidbody;
instantiatedProjectile.velocity = releaseVector * projectileSpeed;
}
}