- Home /
Sync two animations on two different gameObjects
Hi,
I have a top down game, based on grid. Similar to chess. My problem is syncing animations on two different game objects. When two figures meets on neighbouring fields they should play animations of attack and hit until one of them will be killed. For now I using coroutine to handle the fight. In Update I find units, sets they state to busy and start fight coroutine.
IEnumerator Fight(Cell attackerCell, Cell opponentCell, IFightable attacker, IFightable opponent)
{
attackerCell.Unit ().busy = true;
opponentCell.Unit ().busy = true;
int attackerPower = attacker.attack - opponent.defense;
if (attackerPower > 0) {
opponent.health -= attackerPower;
attacker.animator.SetTrigger("Attack");
yield return new WaitForSeconds(attacker.animator.GetCurrentAnimatorStateInfo(0).length);
opponent.animator.SetTrigger("Hit");
yield return new WaitForSeconds(opponent.animator.GetCurrentAnimatorStateInfo(0).length);
if (opponent.health <= 0) {
attackerCell.Unit ().busy = false;
Grid.self.ClearCell(opponentCell);
yield break;
}
}
yield return new WaitForSeconds(1f);
int opponentPower = opponent.attack - attacker.defense;
if (opponentPower > 0) {
attacker.health -= opponentPower;
opponent.animator.SetTrigger("Attack");
yield return new WaitForSeconds(opponent.animator.GetCurrentAnimatorStateInfo(0).length);
attacker.animator.SetTrigger("Hit");
yield return new WaitForSeconds(attacker.animator.GetCurrentAnimatorStateInfo(0).length);
if (attacker.health <= 0) {
opponentCell.Unit ().busy = false;
Grid.self.ClearCell(attackerCell);
GameControll.self.money += 100;
yield break;
}
}
yield return new WaitForSeconds(1f);
attackerCell.Unit ().busy = false;
opponentCell.Unit ().busy = false;
}
Unfortunately it not work. When attack animation is in the middle, hit animation starts and after few iterations I can't say what is going on.
Anyone have any suggestions?
Thanks in advice
Add a debug line after setting the first animation trigger to see what the actual animation length is, or if the animation clip has changed yet. I'm not sure how much of a delay there is with a triggered anim transition, but perhaps it's possible the length that you're using in the WaitForSeconds function is not the value you want.
You could also wait for the normalizedTime to reach 1.0 after verifying the AnimationStateInfo is from the state you want.
Your answer
Follow this Question
Related Questions
2D Animation does not start 1 Answer
Damage gets applied multiple times per frame 0 Answers
2D game animation is running 1 Answer
How to create a 2D rig? 1 Answer
How do i make my attack function not work whilst animation playing? 1 Answer