Calculate closest target

Found an edge case where SetTarget() wouldn’t work :frowning:


If we have 2 targets lined up like in the picture because T2 is closer to the center of the screen SelectTarget() will return T2 instead of T1 which would make more sense given that is closer to the player.

Instead of calculating the distance to the center of the screen why not use distance to the player?
we just need to do:

Vector2 toPlayer = target.transform.position - transform.position;

this way we still only target Targets that are on the screen and will always target the Target that is physically closer to the player.

3 Likes

This is an absolutely valid choice! You can do this either way depending on the targeting style you’re going with. (You could even consider making a keytoggle that switched between center screen (aiming) vs distance). The most important part of the lesson, at least to me, was the quick way of detecting that the enemy was on the screen, which should always be a factor in targeting.

2 Likes

Privacy & Terms