Reputation: 139
I have a little question.
I'm making a simple board game. The user has the possibility to play against an AI. It works fine. The rules of the games state that if someone throws the dice and make 1 or 4, he can play again. So I made a for loop. It works too. The AI plays as many times as it need then allows P1 to play.
My problem is that all animations for the movements of the pawn happen at the same time.
Exemple: AI's turn: 4. Plays again: 1. Plays again: 5. Player's Turn. The animations for 4 & 1 & 5 all plays at the same time (looks weird). I'd like a 2 seconds delay between the first throw from AI and the next one so that the animation have time to play out.
I read that I should use a timer
or a setInterval
but I don't really know where and how to place it in my loop. Here is a sample version of my code if it helps:
EDIT: Updated code, thanks to the answer below:
function fnTimeOut() {
var intervalId: uint = setTimeout(fnNextPlayer, 2000, null);
}
next.addEventListener(MouseEvent.CLICK, fnNextPlayer);
function fnNextPlayer (e:Event):void{
if (player2.currentFrame == 2) { //AI's turn
randDice=random(1, 6); //dice thrown (have a random function setup already)
if (randDice==1){
//start animation
//move pawns
fnTimeOut(); //restarts the function after 2secs
}
if (randDice==2){
//start animation
//move pawns
player2.gotoAndStop(1); //starts player1's turns
//stop loop because not 1 or 4
}
}
}
}
I hope someone can help me :) Thanks.
Upvotes: 0
Views: 433
Reputation: 1438
You have a lot of options. For example: you can add 2 seconds in timeline of animation and listen for animation end. Or you remove for loop and start timeout after each step. Something like this: Write a method which will make the decision for current step:
function MakeDecision()
{
switch( state ):
case( state1):doSomething1()
case( state2 ):doSomething2()
}
where
function doSomething1()
{
..your game code
startTimer for 2s , and call MakeDecision()
}
Or you can make a game loop which will call MakeDecision on regular time and the game will be controlled only by states
Upvotes: 1