Hi,
I’m working on a basic movement tree with root motion inthe new inout system.
I can go to walk or run from idle. But when I try to keep running by hlding the joystick and the run button it stutter steps between walking and running. I am assuming that the problem is in my logic in the HandleMovement function.
parameter isWalking is used in the movement tree to set up transition to walkng and isRunning for in and out of running.
Here is my code:
public class CharacterMovement : MonoBehaviour
{
Animator animator;
int isWalkingHash;
int isRunningHash;
PlayerInput input;
Vector2 currentMovement;
bool movementPressed;
bool runPressed;
void Awake()
{
input = new PlayerInput();
input.CharacterControls.Movement.performed += ctx => {
currentMovement = ctx.ReadValue<Vector2>();
movementPressed = currentMovement.x != 0 || currentMovement.y != 0;
};
input.CharacterControls.Run.performed += ctx => runPressed = ctx.ReadValueAsButton();
input.CharacterControls.Movement.canceled += ctx => movementPressed = false;
}
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
isWalkingHash = Animator.StringToHash("isWalking");
isRunningHash = Animator.StringToHash("isRunning");
}
// Update is called once per frame
void Update()
{
handleMovement();
handleRotation();
}
void handleRotation()
{
Vector3 currentPosition = transform.position; ;
Vector3 newPosition = new Vector3(currentMovement.x, 0, currentMovement.y);
Vector3 positionToLookAt = currentPosition + newPosition;
transform.LookAt(positionToLookAt);
}
void handleMovement()
{
bool isRunning = animator.GetBool(isRunningHash);
bool isWalking = animator.GetBool(isWalkingHash);
if (movementPressed && !isWalking)
{
animator.SetBool(isWalkingHash, true);
}
if ( runPressed )
{
animator.SetBool(isRunningHash, true);
}
if (!movementPressed && isWalking)
{
animator.SetBool(isWalkingHash, false);
}
if (movementPressed && runPressed && !isRunning)
{
animator.SetBool(isRunningHash, true);
animator.SetBool(isWalkingHash, false);
}
if (movementPressed && runPressed && isRunning)
{
animator.SetBool(isWalkingHash, false);
animator.SetBool(isRunningHash, true);
}
if ((movementPressed || !runPressed) && isRunning)
{
animator.SetBool(isRunningHash, false);
}
}
void OnEnable()
{
input.CharacterControls.Enable();
}
void OnDisable()
{
input.CharacterControls.Disable();
}
}