- Home /
How to play correct animation based on direction?
I am making a tower defense game and I am using 2d toolkit to animate the creeps. I have 4 animations for left, right, up and down movement. I also have the direction vector of the creep.
How do I decide which animation to play using the direction vector?
Even if the creep is move at an angle I should still select one of these animations.
Looking for a simple method to decide on the correct animation.
Which animation do you want to be played if the creep moves at a 45 degree angle, e.g. towards (1, 1)?
Answer by 2d4Games · Aug 15, 2013 at 02:12 PM
Assuming the creep can only move in 4 directions (up, down, left right), you could make a series of if statements checking for the direction.
if (directionVector.x == 1 && directionVector.y == 0){
//direction is right
} else if (directionVector.x == -1 && directionVector.y == 0){
//direction is left
} else if (directionVector.x == 0 && directionVector.y == 1){
//direction is up
} else if (directionVector.x == 0 && directionVector.y == -1){
//direction is down
}
Then, in each of the if statements, you can use a 2d toolkit object called tk2dSpriteAnimator. Save the 4 animations as tk2dSpirteAnimationClips, and then you can use
tk2dSpriteAnimator.Play(tk2dSpriteAnimationClip clip);
to play the specific animation. So your final code segment should be something like:
var animator : tk2dSpriteAnimator;
var rightAnim : tk2dSpriteAnimationClip;
var leftAnim : tk2dSpriteAnimationClip;
var upAnim : tk2dSpriteAnimationClip;
var downAnim : tk2dSpriteAnimationClip;
if (directionVector.x == 1 && directionVector.y == 0){
animator.Play(rightAnim);
} else if (directionVector.x == -1 && directionVector.y == 0){
animator.Play(leftAnim);
} else if (directionVector.x == 0 && directionVector.y == 1){
animator.Play(upAnim);
} else if (directionVector.x == 0 && directionVector.y == -1){
animator.Play(downAnim);
}
EDIT: Just noticed that you also wanted them to move at an angle. In that case you check which direction that angle is closest to (like any angle between 45 degrees and 135 degrees would play an up animation). Again, this can be done with a variety of if statements.
var movementAngle = Mathf.Atan(directionVector.y/directionVector.x);
if (movementAngle >= Mathf.PI/4 && movementAngle < 3*(Mathf.PI/4)){
//go up
} else if (movementAngle >= 3*(Mathf.PI/4) && movementAngle < 5*(Mathf.PI/4)){
//go left
} else if (movementAngle >= 5*(Mathf.PI/4) && movementAngle < 7*(Mathf.PI/4)){
//go down
} else {
//go right
}
I know this is super old, but thank you. I knew what I had to do but had no idea how to work out the math behind it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613112245im_/https://answers.unity.com/themes/thub/images/avi.jpg)