- Home /
Play appropriate animation based on character's direction (2D point and click)
I have a simple script to control player movement:
void MovePlayer(){
if (Input.GetMouseButtonDown(0)) {
target = (Camera.main.ScreenToWorldPoint(Input.mousePosition));
target.z = transform.position.z;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
PlayWalkingAnimation();
}
This enabled me to simply click my mouse anywhere on the screen, and the Player will move to that point.
I have four walking animations (NWSE) that i'd like to play depending on the angle the Player is walking in...if that makes sense...
void PlayWalkingAnimation(movementAngle){
//What is movementAngle???
if (movementAngle >= 45 degrees && movementAngle < 135 degrees){
direction = "walking north";
anim.Play (direction);
} else if (movementAngle >= 135 degrees && movementAngle < 225 degrees)){
direction = "walking west";
anim.Play (direction);
} else if (movementAngle >= 225 degrees && movementAngle < 315 degrees){
direction = "walk south";
anim.Play (direction);
} else {
direction = "walking east";
anim.Play (direction);
}
}
I'm not sure how to get the angle I'm moving in, and if there is any math that might be involved.
Also my if-statements might not be spot on, but this is the general idea of what I'm trying to do...
Answer by Daemonhahn · Nov 09, 2017 at 11:11 AM
You should use a blendtree, that way you wont even need to write code to get this to work!
For more info:
https://docs.unity3d.com/Manual/class-BlendTree.html
and
https://www.youtube.com/watch?v=-UhAAgVjk0A
Good luck! :)
Essentially you make a 2D blend tree, with a point at the top bottom left and right, and one in the centre for your idle animation. You then assign the animations to each of the slots, and give a -1 +1 in the X / Y field respectively to say "this animation is for when we are moving left on the X axis" etc.
Please select my answer as the correct one if I have helped you! :)
Your answer
![](https://koobas.hobune.stream/wayback/20220612142604im_/https://answers.unity.com/themes/thub/images/avi.jpg)