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.
Asked
Active
Viewed 85 times
0
-
If the projectile targets objects with the "Enemy" tag (for example), it won't target anything else. – user3071284 Oct 28 '15 at 14:52
1 Answers
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