How do you compare multiple parts of the same array?

So I’m making a 2D game where you will be jumping between planets to reach your destination and because each level will have a different number of planets, I’ve made a Planet array that holds the position of the transform of that planet, the maximum gravity, the maximum gravity distance, and the distance between the player and the planet.

I want to be able to only enable the gravity for the planet that the player is closest to. So far I’ve established the distance from each player to the planet in the update function as you will be moving. I am now trying to basically make the script compare the distance between the player and the planet for each planet and then enable the gravity for the closest planet only.

If anyone could let me know how to compare the distance, I would be truly grateful.

Here’s the array related part of the Gravity Management script that is placed on the player:

    private void Awake()
    {
        foreach (Planet p in planets)
        {
            planet = p.planet;
            maxGravity = p.maxGravity;
            maxGravityDistance = p.maxGravityDistance;
        }
    }
    void Update()
    {
        foreach (Planet p in planets)
        {
            p.dist = Vector2.Distance(p.planet.position, transform.position);
        }
    }

Thank you!

Planet closestPlanet;
float distanceToClosest = Vector2.Distance(closestPlanet.position, transform.position);

foreach (Planet p in planets)
{
    if(p != closestPlanet)
    {
        float distance = Vector2.Distance(p.planet.position, transform.position);
      
        if(distance < distanceToClosest)
        {
            distanceToClosest = distance;
            closestPlanet = p;
        }
    }
}

Eeeeeh something like this will work. It’s the same principle when you are looking for a min/max number in an array of integers. Store one as a reference, then compare each and every one of them and see if they are closer. If a planet is closer than the currently stored closest planet, that is the new closest planet. You do that for every remaining planet.

It could be improved with some thought and there are some holes here and there (like, your closestPlanet is null at the start), but overall, this will work.

1 Like

Thanks so much!

I’ve just tested it out and it works like a charm! I can’t thank you enough! This had me stuck for ages.

1 Like