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();
}
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
.
CodePudding user response:
First, change the key Action Type
to Button
:
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;