- Home /
how do I find out which object is closer to the finish line?
Hello everyone. I'm making a td game. It so happened that some enemies move faster than others. For the towers, I developed a script that captures the first enemy that comes along and shoots at him until he dies or leaves the affected area. But if someone overtakes a slower enemy, then the tower will shoot at the one it shot at before. She will not beat the enemy who is closer to the finish line, although I would like to implement this. How can this be done? what is the principle of this? I've been trying for 2 weeks, but nothing works...(
void OnTriggerStay2D(Collider2D collider)
{
if (collider.gameObject.tag == "Zombie")
{
if (this.mob == null) this.mob = collider.gameObject;
target = mob.GetComponent<Transform>();
transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles.x, transform.rotation.eulerAngles.y, Mathf.Atan2(target.transform.position.y - transform.position.y, target.transform.position.x - transform.position.x) * Mathf.Rad2Deg + 90);
Fire();
}
}
void OnTriggerExit2D(Collider2D collider)
{
this.mob = null;
}
Answer by Whitewalkergp · Mar 03 at 07:34 PM
this script finds the nearest enemy and returns it. your enemies need to be tagged as Enemy. This script should be put on the towers. you can also check if they are in range. i did not put this condition in the script.
public GameObject FindNearestEnemy()
{
GameObject[] Enemies = GameObject.FindGameObjectsWithTag("Enemy");
float ShortestDistance = Mathf.Infinity;
GameObject NearestEnemy = null;
foreach (GameObject Enemy in Enemies)
{
float distance = Vector3.Distance(transform.position,Enemy.transform.position);
if(Distance<ShortestDistance)
{
ShortestDistance = Distance;
NearestEnemy = Enemy;
}
}
return NearestEnemy;
}
it's a little different. I have a finish line and a crooked road, the enemy then enters the area of action, then leaves it. I want to make sure that the tower attacks the one who is closer to the finish line. my path is a set of points.
You can adapt the code above so that it checks the distance to the finish line instead of the distance to the tower. In the call to Vector3.Distance, replace transform.position
with yourFinishLine.transform.position
.
Answer by DaoGear · Mar 05 at 03:45 PM
If you are using the line, I suggest you use vector3.project. Vector3.distance should only be used for point