- Home /
Mouse Click Walk to Idle Animations
I changed controls to Mouse-Click movement and managed to get my character to walk. However, when it reaches its destination, it won't play the proper idle animations. I can see it playing in the blend tree but not in-game. Upon opening the tree, I see not a single position is being played. Not sure what's going on. Here is the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMouseController : MonoBehaviour
{
[SerializeField] private Animator animator;
[SerializeField] private float speed = 6.0f;
private Vector3 targetPosition;
private bool isMoving = false;
// Start is called before the first frame update
private void Start()
{
animator = GetComponentInChildren<Animator>();
}
//FixedUpdate is called several times per frame
void FixedUpdate()
{
//Executes Left Mouse Click to Move
if (Input.GetMouseButton(0))
{
SetTargetPosition();
}
if (isMoving)
{
Move();
}
}
//Sets the mouse to viewport
void SetTargetPosition()
{
//Converts target positioning to game world positioning
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.z = transform.position.z;
isMoving = true;
}
void Move()
{
Vector3 deltaPosition = targetPosition - transform.position;
Vector3 targetDirection = deltaPosition.normalized;
//Sets Walking Animations
animator.SetFloat("moveX", targetDirection.x);
animator.SetFloat("moveY", targetDirection.y);
//Moves the player
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
//Checks last direction of player
if (targetDirection.x == 1 || targetDirection.x == -1 || targetDirection.y == 1 || targetDirection.y == -1)
{
//Sets Idle Animations
animator.SetFloat("lastMoveX", targetDirection.x);
animator.SetFloat("lastMoveY", targetDirection.y);
//Checks if player has reached destination
if (transform.position == targetPosition)
{
isMoving = false;
}
}
}
}
Comment
Your answer
Follow this Question
Related Questions
How do I stop moving when attacking? 1 Answer
overhead game in 2d world? 0 Answers
[2D]Tank track animation 0 Answers
i have a problem with reloading with Time.time 2d game c# Unity 2020.2 1 Answer