pos.findClosest fails on objects stored in memory



  • I have some objects stored in memory like this:

    {"objectId":"55727e478294311c1a187e0e","pos":{"x":37,"y":42,"roomName":"W3N2"},"type":"constructionSite","priority":0.9}
    

    These objects are contained in a big array ordered by priority. I get the first 5 objects from the array and want to find the closest of those 5. Though it fails somewhere in-engine:

    TypeError: Cannot read property 'undefined' of undefined
        at Grid.setWalkableAt (/opt/PathFinding.js/src/core/Grid.js:117:18)
        at Room.findPath (/opt/engine/dist/game/rooms.js:619:12)
        at RoomPosition.findPathTo (/opt/engine/dist/game/rooms.js:810:19)
        at Array.forEach (native)
        at RoomPosition.findClosest (/opt/engine/dist/game/rooms.js:877:24)
        at Object.module.exports.getBuildJobFor (managers/buildManager:37:33)
        at Object.module.exports.behave (creeps/builder:31:48)
        at main:50:18
    

    Thanks



  • This is the code to find the closest out of the first five:

    var first   = creep.room.memory.jobs.slice(0, 5);
    var closest = creep.pos.findClosest(first);
    


  • Well, I managed to work around it by using the following code:

    var first = creep.room.memory.jobs.slice(0, 5);
    var firstObj = [];

    for(var i in first) {
    firstObj.push(Game.getObjectById(first[i].objectId));
    }

    var closest = creep.pos.findClosest(firstObj);

    Then searching through the original array for objectId == closest.id.

    This is not really a bug, but it would be cool if I could just feed the findClosest an array of objects with a pos or positions property.



  • Easiest way is to implement your findClosest wrapper on the RoomPostion prototype; something like this:
    ```javascript
    RoomPosition.prototype.myGetClosest = function (targets) {
    var me = this;

        if (!targets.length) {
            return null;
        }
    
        var mapToPos = _.map(targets, function(t) {
            var pos = t.pos || t;
            if (!(pos instanceof RoomPosition)) { //assume JSON pos
                pos = new RoomPosition(pos.x, pos.y, pos.roomName);
            }
            return { original: t, range: me.getRangeTo(pos) };
        });
    
        return _.first(_.sortBy(mapToPos, "range")).original;
    
    };