Question by
ASproutingSeed · Dec 05, 2017 at 06:11 PM ·
gameobjectpositiondetectionclosestfront
Detect Closest Game Object (with tag) To The Right Of Player Position (2D)
Hi,
So, following some documentation I was able to find out how to detect the position of the closest empty tagged "Teletarget". However, I am trying to figure out how to detect the position of the closest empty tagged "Teletarget" to the right of the player (2D game). Please help if you can! :)
Here's my current code (that only detects closest, not closest on the right, ahead of the player):
public GameObject findClosestTeleportTarget()
{
gos = GameObject.FindGameObjectsWithTag("TeleTarget");
GameObject closestTele = null;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closestTele = go;
distance = curDistance;
}
}
telePosition = closestTele.transform.position;
return closestTele;
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612144032im_/https://answers.unity.com/themes/thub/images/avi.jpg)