Hi all, what I want is to get closest object depends on one axis only, here is pic
The way I know how to do this returns me the (d1, d2) values, its ok, but not at this point, how can I calculate closest to point object depend on x1,x2 distance??
Hi all, what I want is to get closest object depends on one axis only, here is pic
The way I know how to do this returns me the (d1, d2) values, its ok, but not at this point, how can I calculate closest to point object depend on x1,x2 distance??
Assuming position of 1 is V1, 2 is V2 and origin (circle) is Origin…
if ((V1 - Origin).sqrMagnitude > (V2 - Origin).sqrMagnitude)
//V2 is closer
else
//V1 is closer
As for removing an axis, just set that axis to 0.
There can be many objects, what needs to be changed in this script for example?
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Enemy");
float distance = Mathf.Infinity;
Vector3 position = transform.position;
GameObject closest;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
Nothing? Looks good to me.
Yea, its ok, but it return closest using d1, d2.
I think I need to get sleep, my brains just wont work ![]()
Here is how it can be done lol
using UnityEngine;
using System.Collections;
public class ClosestEnemy : MonoBehaviour {
public GameObject closest;
public Transform cls;
void Update()
{
cls = FindClosestEnemy().transform;
}
GameObject FindClosestEnemy() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Enemy");
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
float curDistance = go.transform.position.x - position.x;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
}