Okashi
Okashi

Reputation: 315

How to make character run using the new input system?

I'm trying to add a running feature to my character controller movement. I want the character to run when the Z key is being held. I'm using the new input system and here is my attempt:

     Vector3 horizontalVelocity;
     [SerializeField] CharacterController controller;
     [SerializeField] float walkSpeed = 10f;
     [SerializeField] float runSpeed = 25f;
     bool running; 
     private void Update()
        {
    if (running)
            {
                moveSpeed = runSpeed;
                horizontalVelocity = (transform.right * horizontalInput.x + transform.forward * horizontalInput.y) * moveSpeed;
                controller.Move(horizontalVelocity * Time.deltaTime);
            }
            else
            {
                moveSpeed = walkSpeed;
                horizontalVelocity = (transform.right * horizontalInput.x + transform.forward * horizontalInput.y) * moveSpeed;
                controller.Move(horizontalVelocity * Time.deltaTime);
            }
}
     public void OnRunning() {
            running = true;
        }

And I handled the Input Action in another class like so:

  [SerializeField] Movement movement;
 PlayerControls controls; 
    PlayerControls.GroundMovementActions groundMovement;
 private void Awake() 
  {
 groundMovement.Running.performed += _ => movement.OnRunning();
}
  private void OnEnable()
    {
        controls.Enable(); 
    }

    private void OnDestroy()
    {
        controls.Disable(); 
    }

enter image description here

it is not working, whether I press the z or not it is just walking normally. Does not run when I hold the z key.

Upvotes: 1

Views: 613

Answers (1)

KiynL
KiynL

Reputation: 4266

First, change the key Action Type to Button:

enter image description here

Make the running variable public. Now directly from the key control code, when pressing the Z key, make running true and if it is canceled, set it to false.

public bool running;
_controls.GamePlay.Running.performed += _ = movement.running = true;
_controls.GamePlay.Running.canceled += _ = movement.running = false;

Upvotes: 1

Related Questions