Search code examples
screeps

Finding closest creep to a given creep


Having significant difficulty finding the closest creep to a creep given that must have a specific set of roles and must not already have a designated partner.

This is for the purpose of setting up dedicated miners and dedicated energy carriers (which must find the closest miner or harvester and carry their energy).

I've tried (where creep variable is the creep running the script):

var nearestMinerCreep = creep.pos.findNearest(Game.MY_CREEPS, {
                filter: function(creep) {
                    return (creep.memory.role == "miner" 
                    || creep.memory.role == "harvester") 
                    && !creep.memory.partner;
                }
            });

But findNearest() seems to have been depricated. Replacing this with variations of findClosestByPath() and findClosestByRange() don't work either. The best I've been able to do is get a creep's position with this:

var nearestPos = (creep.pos.findfindClosestByPath(FIND_MY_CREEPS)).pos;

But this is unfiltered and not specific enough due to the need to transfer energy. Thanks in advance for any help!


Solution

  • Game.MY_CREEPS isn't a correct constant, so I think that may have been part of the problems.

    As written in the API pos.findClosestByPath accepts additional parameters, including a filter function. So the correct code would probably be

     let nMCreep = creep.pos.findClosestByPath(FIND_MY_CREEPS, {
       filter: function(creep) {
         return (creep.memory.role == "miner" 
           || creep.memory.role == "harvester") 
         && !creep.memory.partner;
       }
     });