Question by
jackhamlingthon · May 11 at 12:06 PM ·
c#animationanimator controllercharacter movement
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();
}
}
Comment
Your answer
Follow this Question
Related Questions
How to change the animation speed of a certain animation clip within a blend tree by C# script 0 Answers
Animations get screwed up when I add OnAnimatorMove function 0 Answers
MobController 1 Answer
Animator controller probably messed up, need advice 0 Answers
Why is scripting animation not so responsive in unity? 0 Answers