Not sure where this belongs really, but have an issue where the enemy characters are firing at the player yet they are unable to hit the player directly when the code means they should always hit the player every time when they are stationary.
The circled bullet should hit the middle of the big green block but ill always go over the top,
Code:
//More above this but doesn’t influence the firing
if (Physics.Raycast(player.transform.position,transform.position, out hitInfo))
{
if (hitInfo.distance < maxRange)
{
FireAtPoint(hitInfo.point);
}
// methods
private void FireAtPoint(Vector3 point)
{
// Variables
Vector3 randomAccuracy;
//randomAccuracy = new Vector3(Random.Range(-0.1f,0.1f), 0, Random.Range(-0.1f,0.1f));
// Get the velocity to fire out at
var velocity = FiringVelocity(point, angle);
//Debug.Log("Firing at " + (point + randomAccuracy) + " velocity " + velocity);
Rigidbody rg = Instantiate(bulletPrefab.gameObject, firePoint.position, firePoint.rotation).GetComponent();
//Debug.Log(“Firing at” + transform.position);
EnemyBulletController newProjectile = rg.GetComponent();
newProjectile.speed = velocity;
//Debug.Log(newProjectile.speed);
}
private Vector3 FiringVelocity(Vector3 destination, float angle)
{
// Get the direction of the mouse click from the player, then get the height differential.
Vector3 direction = destination - transform.position;
float height = direction.y;
height = 0;
// Get the distance in a float of the vector3
float distance = direction.magnitude;
// Turn the firing angle into radians for calculations, then work out any height differential
float AngleRadians = angle * Mathf.Deg2Rad;
direction.y = distance * Mathf.Tan(AngleRadians);
distance += height / Mathf.Tan(AngleRadians);
// Calculate the velocity magnitude
float velocity = Mathf.Sqrt(distance * Physics.gravity.magnitude / Mathf.Sin(2 * AngleRadians));
// Debug.Log(velocity);
// Return the normalized vector to fire at.
return velocity * direction.normalized;
}