findNearest, findInRange - How to use in Screeps?

9.5k views Asked by At

I try to use findNearest like that:

var sources = creep.room.findNearest(Game.SOURCES) 
creep.moveTo(sources[0]);
creep.harvest(sources[0]);

and this is what i get:

TypeError: undefined is not a function
at module.exports:5:28
at <main>:11:6

How to use this method and findInRange so that they don't cause this error?

2

There are 2 answers

0
dlkulp On BEST ANSWER

There are several things to note here:

  1. findNearest() is not in the room object. Simple fix var sources = creep.pos.findNearest(Game.SOURCES)
  2. findNearest() does not return an array of objects, it returns one single object (specifically the closest object) or null. The fix here is to change what you have to creep.moveTo(sources); (you might want to make sources singular to avoid confusion)
  3. You didn't provide code but I'm going to guess you're doing something like creep.room.findInRange() and again it's not in the room object it's in pos so it would look like this instead, creep.pos.findInRange().
  4. Confusingly, the only functions in room are find(), lookAt(), findPath(), and makeSnapshot() whereas pos has quite a few more (listed in roomposition in the docs)

If you look in the documentation here for room and here for roomposition and scroll to the bottom you can see which functions are in which object.

1
Krokiet On

As I can see documentation has been updated and now has some sample code.

http://screeps.com/docs/RoomPosition.php