Be the first to post for 'Enemy Move And Attack Spheres'!

If you’re reading this, there probably aren’t very many posts yet. But don’t worry, you can be the first! Either create a new post or just reply to this one to say ‘hi’.

This is the scrnshot of my gizmo setup. I decided that a 7.5m radius would be for the ranged attack range, because after playing diablo 3 and torchlight 2 I realised that, the range for spell casters is fairly large.

1 Like

I found that regular spheres were easier to see when terrain isn’t flat. Alpha is reduced to .25f on the colors.

I’d already added an attack range and an ‘aggro range’ (rather than chase range - I’ll explain below).

But rather than simply subtracting a vector to the player, I wanted my enemies to be able to attack my allies too - so I used Physics.OverlapSphere and checked a layermask for targetable objects that were within that OverlapSphere.

private Transform FindTargetInRange(float aggroRange)
{  
    // See what are in range
    Collider[] opponentsInRange = Physics.OverlapSphere(this.transform.position, aggroRange, opponentLayerMask);

    if (opponentsInRange.Length == 0) { return null; }

    // Find closest in range
    float closestRange = 0;
    Collider closestTarget = null;
    foreach (var opponentInRange in opponentsInRange)
    {
        if (target != null && opponentInRange.gameObject == target.gameObject)  
        {  // keep current target if still in range
            return opponentInRange.transform;
        }
        float currentRange = (transform.position - opponentInRange.transform.position).magnitude;
        if (closestTarget == null || currentRange < closestRange)
        {
            closestTarget = opponentInRange;
            closestRange = currentRange;
        }
    }
    return closestTarget.transform;
}

This makes it work differently to Ben’s code in that it uses this to identify a target and then only if identified, will it move to and attack if in attack range. So, if I have the attack range greater than the chase(aggro) range - then mine will not attack if the player is in the attack range but NOT in the aggro range… if you follow.

I think I’m ok with that.

However, my enemy script is getting a but unwieldy now (especially since I added a lot of code for formations). I think it should really be a generic movement script for all AI friendlies, enemies, neutral etc… and maybe have attacking in a separatescript.

I’m just not too sure if I want to depart too far from Ben’s architecture yet in case it becomes difficult to follow in future lectures.

It’s definitely getting interesting!

Privacy & Terms