Get closest target


I have one enemy prefab and one target prefab. Both are created in a script because it appears at a certain time and in groups.
I wish that an enemy prefab created finds its closest target, and stuck to it until it reaches its position.
I have found several answers in C++ but I am trying to do it in JavaScript.

I have this to find a node position and calculate the distance between the prefab and the node, but the getPosition() doesn’t seem to work for a prefab

var targetPosition =;
var distance = this.node.position.sub(targetPosition).mag();

But then it is just a random target. I am afraid that the enemy will bug since several targetPrefabs are created and it won’t know where to go. which is why I am trying to get the closest target, but I don’t know how
And then I will use moveBy until it reaches its destination :

var enemyTarget = cc.moveBy(100,;

Does anyone has any suggestions ?
Thank you in advance

My first thought was a rayCast() but I looked in the Cocos2d-js API Docs and I didn’t see it available.

But could you pseudo-simulate this behavior by building a space buffer around the object and have it continually check if any other objects cross into the space buffer.

Or you could even start the space buffer around the character and have it grow each frame until the space buffer itself crosses into an object.

Think like various implementations of sonar.

Thank you very much, I will try this idea !