Recently, I decided to abstract input away from the character and into a single InputManager class. This way, player input can be switched to different characters on the fly. I’m already familiar with regular C# events, but I thought I’d give the UnityEvent class a try.
99% of the time, this works as intended and is very responsive. However, every once in a while, the character continues to move for a second or two after the movement key is released.
I figure that it’s probably some sort of timing issue. If somebody could offer any insight, I’d really appreciate it. Code is below.
public class InputManager : MonoBehaviour
{
private Vector3 inputMoveDirection;
public InputMoveEvent inputMove;
void Start()
{
inputMoveDirection = new Vector3(0f, 0f, 0f);
if (inputMove == null)
{
inputMove = new InputMoveEvent();
}
// TODO: Temporary Test Code!
CharacterControl controller = GameObject.FindGameObjectWithTag("Player").GetComponent<CharacterControl>();
inputMove.AddListener(controller.OnInputMove);
}
void Update()
{
inputMoveDirection.x = Input.GetAxis("Horizontal");
inputMoveDirection.z = Input.GetAxis("Vertical");
inputMove.Invoke(inputMoveDirection);
}
}
public class InputMoveEvent : UnityEvent<Vector3> { }
public class CharacterControl : MonoBehaviour
{
private Rigidbody myRigidbody;
private CharacterState characterState;
void Start()
{
myRigidbody = GetComponent<Rigidbody>();
characterState = this.GetComponent<CharacterState>();
}
public void OnInputMove(Vector3 inputMoveDirection)
{
// TODO: This works 99% of the time, but every once in a while, the character continues to move for a second after input has been released
if (characterState.isGrounded)
{
myRigidbody.velocity = inputMoveDirection.normalized * characterState.moveSpeed;
}
}
}