2D blend tree Idle problem
Firstly I created a 4 directions blend tree (Left, Right, Up and Down).
Next I create a click to mouse script and attached it to my player.
Then I change my script a bit to make sure my player goes it all 4 directions, this is my script now:
private Animator anim;
public float speed = 15f;
private Vector3 target;
void Start () {
target = transform.position;
anim = GetComponent<Animator> ();
}
void Update () {
if (Input.GetMouseButtonDown(0)) {
Vector3 mousePosition = Input.mousePosition;
mousePosition.z = 10; // distance from the camera
target = Camera.main.ScreenToWorldPoint(mousePosition);
target.z = transform.position.z;
}
var movementDirection = (target - transform.position).normalized;
if (Input.touchCount > 0)
{
target.x = Input.touches[0].deltaPosition.x;
target.y = Input.touches[0].deltaPosition.y;
}
transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);
anim.SetFloat("SpeedX", movementDirection.x);
anim.SetFloat("SpeedY", movementDirection.y);
}
void FixedUpdate () {
float LastInputX = transform.position.x - target.x;
float LastInputY = transform.position.y - target.y;
if (LastInputX != 0 || LastInputY != 0) {
anim.SetBool ("walking", true);
if (LastInputX > 0) {
anim.SetFloat ("LastMoveX", 1f);
} else if (LastInputX < 0) {
anim.SetFloat ("LastMoveX", -1f);
} else {
anim.SetBool ("walking", false);
}
if (LastInputY > 0) {
anim.SetFloat ("LastMoveY", 1f);
} else if (LastInputY < 0) {
anim.SetFloat ("LastMoveY", -1f);
} else {
anim.SetFloat ("LastMoveY", 0f);
}
} else {
anim.SetBool ("walking", false);
}
}
I then tested it out, but only to find that my LastMoveX and LastMoveY function isn't being called properly. What I mean is that when I clicked to the left my player goes there but it flips right in the process and when it finally reached it's position overall it faced right. It also did the same when I clicked to the right. Another problem I found was when I move down the Y axis. My animation kept on playing and wasn't stopping until I clicked somewhere else for example above the player. How can I make my LastMoveX and LastMoveY function properly? Thank you!