Skip to content

Movement optimisations

Warren Earle edited this page Jun 23, 2016 · 5 revisions

The creep.moveTo method used in the tutorial example is a HIGH CPU cost

Find the optimal path to the target within the same room and move to it. A shorthand to consequent calls of pos.findPathTo() and move() methods. If the target is in another room, then the corresponding exit will be used as a target. Requires the MOVE body part.

moveTo(x, y, [opts])

moveTo(target, [opts])

the method has the following arguments:

##Arguments

###x number X position of the target in the same room.

###y number Y position of the target in the same room.

###target object

  • Can be a RoomPosition object or any object containing RoomPosition. The position doesn't have to be in the same room with the creep.

###opts (optional) object

An object containing additional options:

###reusePath number

This option enables reusing the path found along multiple game ticks. It allows to save CPU time, but can result in a slightly slower creep reaction behavior. The path is stored into the creep's memory to the _move property. The reusePath value defines the amount of ticks which the path should be reused for. The default value is 5. Increase the amount to save more CPU, decrease to make the movement more consistent. Set to 0 if you want to disable path reusing.

###serializeMemory boolean

If reusePath is enabled and this option is set to true, the path will be stored in memory in the short serialized form using Room.serializePath. The default value is true.

###noPathFinding boolean

If this option is set to true, moveTo method will return ERR_NOT_FOUND if there is no memorized path to reuse. This can significantly save CPU time in some cases. The default value is false.

Any options supported by Room.findPath method.

Examples

creep.moveTo(10, 20);

creep.moveTo(Game.flags.Flag1);

creep.moveTo(new RoomPosition(25, 20, 'W10N5'));

creep.moveTo(pos, {reusePath: 50});

creep.moveTo(targets,{reusePath: 10});

// Execute moves by cached paths at first 
for(var name in Game.creeps) {                                  //var name is a statement executed before the loop
   Game.creeps[name].moveTo(target, {noPathFinding: true});
}

// Perform pathfinding only if we have enough CPU
if(Game.cpu.tickLimit - Game.cpu.getUsed() > 20) {
    for(var name in Game.creeps) {
        Game.creeps[name].moveTo(target);
    }
}   

the for/in loops through the properties of an object

in this case the object is Game.creeps the name is Creep’s name. You can choose the name while creating a new creep, and it cannot be changed later. This name is a hash key to access the creep via the Game.creeps object.

Clone this wiki locally