- Home /
Play different animations based on direction character is facing, while following the mouse.
I have a character in a top down game moving as per the motion of the mouse. How do I play the respective animation based on the direction, the character is facing at any moment ? Kindly note that my character sprite is not as if it is being seen from 90 degrees over its head, but as if the character is seen from its' side. So, I don't the game object to rotate, but just switch animations based on the direction it is facing. I tried doing Mathf.Abs to check for Horizontal and Vertical axes but it didn't work. Here is the code for my character movement based on the movement of the mouse.
private Vector3 mousePosition;
public float moveSpeed = 0.1f;
float speed = 1.0f;
void Start () {
Screen.showCursor = false;
}
void Update () {
if (Input.GetMouseButton(0)) {
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = Vector2.Lerp(transform.position, mousePosition, moveSpeed);
}
}
}
Answer by Mikael-Gyth · May 01, 2014 at 08:46 AM
vector2 direction = transform.position - mouseposition;
Will give you the direction and distance from the character towards the mouseposition. You can use this to determine where the mouse is in relation to the character.
if you only need to check left/right you can simply check if direction.x is positive or negative. This can also be combined with direction.y to check if the mouse is above or below the character.
BTW: Mathf.abs returns the absolute value of a specified number. So -1 would be 1, and 1 would be 1 also.
I do want the direction to be checked in X as well as Y. How exactly do I use this code to assign an animation to the directions ? Also, this can work for the horizontal and vertical directions, but how would it be possible to assign an animation to a diagonal movement ?
Play.SetFloat ("speed", vector2 direction = transform.position - mouseposition);
This gives an error that says - Unexpected symbol 'direction'
Your answer
Follow this Question
Related Questions
Playing animations by velocity for the correct direction. 0 Answers
Animated sprites disappear when rotating 0 Answers
Nav mesh agent moves backwards - How can I rotate gameobject without using an empty 1 Answer
Make the player go into the direction I am looking at 0 Answers
Can the animation editor create local rotational data? 3 Answers