'Player animation doesn't want to stop
Currently working on a mobile game where i need to move the character with a virtual joystick ,i used a code from a tutorial i saw on the internet, the problem is when i move the joystick the character moves in the right direction and the animation works fine but when i release it the character doesn't stop
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
public class CharacterMovement : MonoBehaviour
{
private CharacterController controller;
private Vector3 playerVelocity;
private bool groundedPlayer;
private Animator animator;
private PlayerInput input;
private InputActionAsset asset;
private Transform cameraTransform;
private float playerSpeed = 2.0f;
private float gravityValue = -9.81f;
int isWalkingHash;
Vector2 currentMovement;
bool movementPressed;
private void Awake()
{
input = new PlayerInput();
input.CharacterControls.Move.performed += ctx =>
{
currentMovement = ctx.ReadValue<Vector2>();
movementPressed = currentMovement.x != 0 || currentMovement.y != 0;
};
}
private void Start()
{
controller = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
isWalkingHash = Animator.StringToHash("isWalking");
cameraTransform = Camera.main.transform;
}
void Update()
{
HandleMovement();
groundedPlayer = controller.isGrounded;
if (groundedPlayer && playerVelocity.y < 0)
{
playerVelocity.y = 0f;
}
Vector2 inputs = input.CharacterControls.Move.ReadValue<Vector2>();
Vector3 move = new Vector3(inputs.x, 0, inputs.y);
controller.Move(move * Time.deltaTime * playerSpeed);
if (move != Vector3.zero)
{
gameObject.transform.forward = move;
}
playerVelocity.y += gravityValue * Time.deltaTime;
controller.Move(playerVelocity * Time.deltaTime);
}
void HandleMovement()
{
bool isWalking = animator.GetBool(isWalkingHash);
if (movementPressed && !isWalking)
{
animator.SetBool(isWalkingHash, true);
}
if (!movementPressed && isWalking)
{
animator.SetBool(isWalkingHash, false);
}
}
private void OnEnable()
{
input.CharacterControls.Enable();
}
private void OnDisable()
{
input.CharacterControls.Disable();
}
}
Solution 1:[1]
I think the problem is in the HandleMovement()
method. First of all I don't think you even need bool isWalking = animator.GetBool(isWalkingHash);
. Also use an else
statement after if (movementPressed && !isWalking) { animator.SetBool(isWalkingHash, true); }
. You don't need the 2nd if
statement if you use else
.
Also according to you code isWalkingHash
is a int
variable defined in the script and for animator.SetBool(isWalkingHash, false);
to work you have to pass the name of the boolean parameter deined in the parameter section in the animator as a string.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sathika Hettiarachchi |