0

In my game a player can fire a weapon which will launch a projectile that automatically targets the enemy who is closest to a certain object. However, how can I stop the projectile from also targeting my own player? Is there any way to tag all other players with a certain tag, whilst leaving my own player with a different tag? The players are instantiated as prefabs when the game starts.

user3071284
  • 6,955
  • 6
  • 43
  • 57
Letsgo66
  • 11
  • 2

1 Answers1

1

When launching the projectile, give it a reference to the player who shot it. Then, when calculating the closest player, check if the closest is the same as the one who shot it. If he is, choose the second closest.

public class Projectile : MonoBehaviour
{

    public Player player = null;
    private Player target = null;

    private Player GetClosestPlayer(IList listOfPlayers)
    {
        Player closestPlayer = ...; // use your algorithm method here

        if (player != null && player == closestPlayer)
        {
            // copy listOfPlayers and remove closestPlayer from it
            return GetClosestPlayer(copyOfListOfPlayersWithoutPreviousClosest);
        }

        return closestPlayer;

    }

    void Update()
    {
        if (target != null)
            // steer to target
        else
            target = GetClosestPlayer();
    }

}
Raimund Krämer
  • 1,255
  • 1
  • 11
  • 29