...

View Full Version : Flow control....issue



nuBee
12-12-2011, 02:59 AM
edit::I guess I tried everything else before thinking of a toggle variable....seems to be working now

I have an if clause that triggers died();


died() {
monster.y=-100; //move element off canvas
setTimeout("respawn()", 2500);
}

respawn() {
//move monster to random location inside canvas
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
}

if(collision condition true) {
died();
}

This works but it sends setTimeout("respawn()",2500); about a dozen times, so 2.5 seconds later when it respawns it runs a dozen times and the monster flickers around the canvas before finding it's final destination.

I've tried both a WHILE loop which WORKED initially but I couldn't get it to reset properly, it worked the first time it ran and that was it....

I tried an if() with a global variable called count so it would only be called if count was under 2 but it didn't work right....

I tried a for loop as well. But my main() function is running every 10ms, and it just triggers things so fast that it triggers things multiple times when I only want it to fire once....

pseudo of what I'm trying to do.

If(collision) {died();}
died(){ move char off viewable screen, delay 2.5 seconds before moving back onto screen at random location}

Seems so simple......but when there's a collision, it sends died() every pixel as the 2 objects move across each other.....where I need it to only trigger died after the first collision is detected and stop checking for 2.5 seconds or the duration of the wait before showing back up on the screen..

so maybe I need a new function to call died which can only be called once....

Old Pedant
12-12-2011, 06:29 AM
Ready to kick yourself?


var waiting = null;
function died() {
if ( waiting == null )
{
waiting = setTimeout(respawn, 2500); // no quotes around respawn and no parens
monster.y=-100; //move element off canvas
}
}

function respawn() {
waiting = null; // allow the die to set the timeout again

//move monster to random location inside canvas
monster.x = 32 + (Math.random() * (canvas.width - 64));
monster.y = 32 + (Math.random() * (canvas.height - 64));
}

if(collision condition true) {
died();
}

Just don't allow a setTimeout if one is already running!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum