Right now I am working on a simple tank AI - it drives through the level and shoots at any enemy objects in range. There's no physics involved except for a constant velocity added to missile's velocity to account for tank's velocity - the code looks like this:
private void Update()
{
if (Time.time - _lastMissileTime < _missileCooldown)
{
return;
}
Enemy target = GetClosestEnemy();
if (target == null)
{
return;
}
Vector3 shootDirection = target.transform.position - transform.position;
Shoot(shootDirection);
_shotTargets.Add(target);
_lastMissileTime = Time.time;
_targets.Clear();
}
private Enemy GetClosestEnemy()
{
foreach (Enemy enemy in _enemies)
{
if (_shotTargets.Contains(enemy))
{
continue;
}
if (Vector3.Distance(transform.position, enemy.transform.position) > _missileRange)
{
continue;
}
_targets.Add(enemy);
}
if (_targets.Count < 1)
{
return null;
}
_targets.Sort((x, y) => Vector3.Distance(x.transform.position, transform.position).CompareTo(Vector3.Distance(y.transform.position, transform.position)));
return _targets[0];
}
private void Shoot(Vector3 direction)
{
direction.Normalize();
Missile missile = Instantiate(_missilePrefab, transform.position, Quaternion.LookRotation(direction));
Vector3 tankVelocity = _mover.Direction * _mover.Speed;
Vector3 missileVelocity = direction * _missileSpeed + tankVelocity;
missile.Initialize(missileVelocity, _missileLifetime);
}
Here's how it looks like in debug view - yellow lines are for the direct trajectory to target, red lines show the actual trajectory of a missile.
https://gfycat.com/lavishcautiousgrayfox
Now I want to add different levels of experience to my tank AI so veteran level tanks will hit more often - while I could simply remove the tanks velocity from missile velocity calculation for veteran tanks it kinda feels hacky. I would like to determine what direction the tank has to shoot at to compensate for additional velocity but I simply can't figure it out. I tried simulating the actual shot direction and offseting the direct direction to the target by it but it doesn't work most of the times. I would love any help and ideas!