Movement value is reset before it can get cancelled by a UnityEvent

33 Views Asked by At

I've been using Unity for a few days and I'm trying to create a simple plateformer. I'm currently doing the basic player character physics, but I'm trying to use the "new" InputSystem and my character movement only happens for 1 frame each press instead of being able to hold it down.

I tried a few things like adding conditions that check the Callback on its sarted and performed states, I have identified that the issue is that the function itself instantly resets the values because it goes and gets the ReadValue 1 too many times or at least it seems that way.

The input function

The console prints

I've been struggling with it for a while and I can't find a solution because the events that the InputSystem uses seem to be called at times that I can't control without completely side stepping the UnityEvents and going with my own, which is a pain and the point of this little project is to learn to use the UnityEvents and InputSystem better. I've also made sure that I am not stupidly resetting movement.x anywhere else in the code multiple times.

Other useful parts of code

The more I try things out the more it seems that the issue is that the ReadValue().x is applied to movement.x one too many times when itself is set at 0 before the event gets cancelled, and I can't find a solution.

1

There are 1 best solutions below

1
Gaspard GUILLOT On BEST ANSWER
public void InputHorizontal(InputAction.CallbackContext context) {
  if (context.started)
  {
    if (context.ReadValue<Vector2>().x != 0)
    {
      playerStates |= States.Walking;
      if (context.ReadValue<Vector2>().x < 0f)
      {
        playerStates &= ~States.FacingRight;
        playerStates |= States.FacingLeft;
      }
      if (context.ReadValue<Vector2>().x > 0f)
      {
        playerStates &= ~States.FacingLeft;
        playerStates |= States.FacingRight;
      }
    }
  }
  if (context.canceled)
  {
    playerStates &= ~States.Walking;
  }
}

void AddMovement() {
  if (playerStates.HasFlag(States.Walking) || speed > 0)
  {
    if (playerStates.HasFlag(States.FacingRight))
    {
      movement.x = 1;
    }
    else
    {
      movement.x = -1;
    }
  }
}

I fixed it by side stepping the issue.

Now the movement doesn't actually directly depends on the context.ReadValue and it works. Which does confirm that the InputSystem does call the function one too many times through the started and performed events.