Hello, i want to make an object move to the closest available position that matches a given criteria. In this case something like
if(Input.GetAxisRaw("Horizontal") != 0)
{
/*move to the object with the closest horizontal position in the pressed direction.
something like getting an array of gameobjects, and then deciding which one is closest
to this object's position */
}
I remember doing this once before, something like getting an array and checking which was closest to gameobject.transform.position.x + input.getaxisraw(“Horizontal”), but i cannot remember what i did to make that calculation.
You just have to iterate over all of the objects you’re interested in and calculate the distance. Find the one with the smallest distance. A little more efficient if you use Vector3.SqrDistance instead of Vector3.Distance. Since you’re only interested in one “side”, you should also throw out any objects that are not on that side by comparing the X component of your object with each object.
If you just need to know which object is the farthest to the left in a scene, you don’t actually need to use any distance calculations; you can simply just find the object with the lowest X-position value.
Given a collection of GameObjects, loop through and compare the X-position of each, caching the object with the lowest value and returning it at the end of the loop:
i used 100f because that makes it so that no matter how far to the left/right the object is, this method should be able to find it. as for why it’s multiplied by (Direction * -1), its just to make it easier to read IMO, as its called with -1 for left and positive 1 for right
To make it work both ways, it may be easier to just write a struct that contains the farthest objects in both directions that will be returned by the method, and the method would just calculate both directions at the same time.
Something like this:
public readonly struct FarthestObjects {
public GameObject FarthestObjectLeft { get; }
public GameObject FarthestObjectRight { get; }
public FarthestObjects(GameObject farthestLeft, GameObject farthestRight) {
FarthestObjectLeft = farthestLeft;
FarthestObjectRight = farthestRight;
}
}