I am trying to make an AI enemy shoot projectiles at the player taking into account their speed to shoot in front of them in the direction they are going. The projectile detects the player and shoots every second, but is just shooting straight. I am not sure if I am calculating the target wrong or not aiming the projectile correctly.
This is a simplified version to drop into an object to test with a projectile. Any thoughts? Is there anything else I should be calculating for this?
public class AIShootProjectile : MonoBehaviour
{
public GameObject projectile;
public SphereCollider sensorTrigger = null;
public float shootForce;
public float attackCoolDown = 1;
private float timer;
private Vector3 targetpos;
private float distanceToTarget;
private Vector3 targetDirection;
private float targetSpeed;
void Update()
{
timer += Time.deltaTime;
if (timer >= attackCoolDown) // if using ammo, add (&& ammo >= 1)
{
ShootProjectile();
}
}
// AI has a large Sphere Collider attached to detect collisions of potential threats
// When there is a collider,
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
// Get target info
Vector3 velocity = other.attachedRigidbody.velocity;
targetSpeed = velocity.magnitude;
targetpos = other.transform.position;
distanceToTarget = Vector3.Distance(sensorTrigger.transform.position, other.transform.position);
targetDirection = other.transform.forward;
}
}
void ShootProjectile()
{
float projectileSpeed = shootForce;
float projectileTimeToTarget = distanceToTarget / projectileSpeed;
float projectedTargetTravelDistance = targetSpeed * projectileTimeToTarget;
Vector3 projectedTarget = targetDirection * projectedTargetTravelDistance;
projectedTarget.y += 1; //aim at center of target if 2m high
GameObject go = Instantiate(projectile, transform.position, Quaternion.identity);
go.transform.LookAt(projectedTarget);
Rigidbody rb = go.GetComponent<Rigidbody>();
rb.velocity = go.transform.forward * shootForce;
rb.useGravity = true;
timer = 0f;
}
}