Why aren't they moving anymore?
There could be a few reasons for this:
If the variable NPCid
is not defined anywhere: Your code will throw a ReferenceError
.
If NPCid
is defined but not globally: Passing a string into setTimeout
won't evaluate it in the current context, causing issues with accessing NPCid
. It's generally advised not to pass strings into setTimeout
.
If NPCid
is global: During execution of delayed code, all instances will see the same value of NPCid
, which is its final value at the end of the loop.
To resolve this, if you're working on NodeJS (assuming from your approach), you can try:
PS.Tick = function ()
{
"use strict";
// (Assuming NPCid is declared; add `var NPCid;` here if needed)
for (NPCid = 0; NPCid < NPCnumber; NPCid++)
{
var timeout = 0;
timeout = PS.Random(1000);
setTimeout(NPCAI, timeout, NPCid); // Only for NodeJS and Firefox!!
}
};
This method works because NodeJS (and Firefox) allow passing arguments to setTimeout
for the called function.
If not using NodeJS or Firefox, but having ES5's Function#bind
, consider:
PS.Tick = function ()
{
"use strict";
// (Assuming NPCid is declared; add `var NPCid;` here if needed)
for (NPCid = 0; NPCid < NPCnumber; NPCid++)
{
var timeout = 0;
timeout = PS.Random(1000);
setTimeout(NPCAI.bind(undefined, NPCid), timeout);
}
};
Function#bind
generates a function that calls the original function with specified this
value and provided arguments.
If unavailable, create a custom bind
or opt for:
PS.Tick = function ()
{
"use strict";
// (Assuming NPCid is declared; add `var NPCid;` here if needed)
for (NPCid = 0; NPCid < NPCnumber; NPCid++)
{
var timeout = 0;
timeout = PS.Random(1000);
setTimeout(makeHandler(NPCid), timeout);
}
function makeHandler(id) {
return function() {
NPCAI(id);
};
}
};
This solution involves creating a function that, upon invocation, triggers the appropriate call to NPCAI with the provided argument value.