[SOLVED] How to find the nearest in an array

I want my enemy to use the nearest ladder. To do this, I first find all ladders in my game and then I have to determine which one is closest. I probably have to find and store all distances and compare them, but I don’t know how to combine these things. Who can help me with this?

 var ladders = this.app.root.findByTag("Ladder");
 ladders.forEach( function(ladderEntity){
     if (ladderEntity.enabled) {
        // check distance and find the nearest
     }
 }.bind(this));

Normally, you keep track of the entity and the closest distance and check against that in the loop. eg

var closestLadder = null;
var closestDistance = 1000000;

  var ladders = this.app.root.findByTag("Ladder");
 ladders.forEach( function(ladderEntity){
     if (ladderEntity.enabled) {
        var distance = playerPosition.distance(ladderEnitity.getPosition());
        if (distance < closestDistance) {
            closestDistance = distance;
            closestLadder = ladderEntity;
        }
     }
 }.bind(this));
1 Like

That’s an easy way. I thought a little too difficult. Is the line after that forEach executed after all ladders have been checked for distance? Also I like to know what the difference is between using forEach and a for loop.

Yes. Each item will be checked to see if it is enabled or not.

Functionally there isn’t a difference. They both do the same thing. What is different is compatibility. forEach() is only compatible with browsers supporting ES5.

edit: wrong ES standard

I mean, if I send the enemy to the closest ladder in the line after that forEach loop, have all the ladders already been passed or is there a risk that this loop has not been completed yet?

Good to know, then I can use forEach in all cases.

@eproasim I think forEach is available in ES5.

@Albertos, essentially both methods do the same thing - they iterate over an array. The difference is that forEach executes a provided function on every single element in that array. You can’t break and exit the loop early, for example. Or you can’t start the loop from the middle of array. The loop will start from the beginning and end when there are no more elements to loop in the array.

If you need to exit the loop early or have control over the iteration step, then you should use for loop, where you can use keywords break to exit loop and continue to skip an element to the next one.

2 Likes

Ah clearly. Thanks. So a for loop offers a bit more options if you need it.

Now I just want to know if a loop has been completed in the first line after the loop or could it be that the loop has not finished yet?

Sorry! I misunderstood. Yes. Lines after the forEach will occur after the loop has completed as forEach is not an asynchronous function.

2 Likes

Thank you all, I think I will be able to do this with this information.

1 Like