Scanning For Nearest Target


(I'm not sure if this is a widely used technique, but it's how I do it in Unity)

To check for the nearest target:

1) Have a Game Object with a Sphere Collider as a child of the character.

2) Add a simple animation to the Game Object to basically have the Sphere Collider 'grow' outwards from the character. Make sure this is on loop.

There are then 2 scenarios that need to be taken into account:

A) If the character currently has NO target:  The moment the collider hits an enemy (based on a tag, like "enemy"), that enemy is now the character's current target.

///////////////////////////////////////////////////////////////////////

Pseudo code:

if(character.target == null)

{

if(collider.hit == "enemy")

character.target = hit.enemy;

}

///////////////////////////////////////////////////////////////////////

B) If the character currently has a target: The distance of the current target is always kept track of via script. If the collider, while looping its animation, hits an enemy that is closer than the current target, this new enemy becomes the current target.

///////////////////////////////////////////////////////////////////////

Pseudo code:

if(character.target != null)

{

closest.enemy.distance = distance.between(character,character.target);

if(collider.hit == "enemy")

{

if(new.enemy.distance < closest.enemy.distance)

{character.target = new.enemy;

closest.enemy.distance = new.enemy.distance;}

}

}

///////////////////////////////////////////////////////////////////////

There are, of course, other factors to take into account:

1) What if the 'new' enemy is not supposed to be target-able? E.g. its HP is 0 and is KO-ed. Solution: Boolean check this.

2) If the character were to get far away enough from the current enemy, character.target should be nullified, and the closest.enemy.distance should be set to a high value such as 1000 (i.e. re-initiating the closest enemy distance).

This seems to work so far for my game. Check out how it's working in this clip:

Get Tikus Tales (Demo)

Download NowName your own price

Leave a comment

Log in with itch.io to leave a comment.