Home > database >  How to change speed when crouching?
How to change speed when crouching?

Time:06-01

I'm trying to make the player slower when he moves while crouching.

private float moveSpeed = 5f;
private float crouchSpeed = 0.2f;
private float runSpeed = 8.5f;    
private void PlayerMovement() 
{
    move = controls.Player.Movement.ReadValue<Vector2>();
    movement = (move.y * transform.forward)   (move.x * transform.right);
    controller.Move(movement * moveSpeed * Time.deltaTime);
    
    if (isRunning)
    {
        run = controls.Player.Run.ReadValue<float>();
        Vector3 running = (move.y * transform.forward)   (move.x * transform.right);
        controller.Move(running * runSpeed * Time.deltaTime);
    }
    if (crouching)
    {
        isRunning = false;
        transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
        movement = (move.y * transform.forward)   (move.x * transform.right);
        controller.Move(movement * crouchSpeed * Time.deltaTime);
    }
    else
    {
                
        transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
        movement = (move.y * transform.forward)   (move.x * transform.right);
        controller.Move(movement * moveSpeed * Time.deltaTime);
    }
}

However, it is still the same speed as walking speed even when the player crouches. Why is that?

CodePudding user response:

A good way to set speed is to delete duplications of same method. In this way you can define a temporary speed variable and pass it through different conditions to finally determine the main speed. In this method, you no longer need to redefine Character.Move and the problem will be solved.

var currentSpeed = moveSpeed;
if (isRunning)
{
    currentSpeed = runSpeed;
    run = controls.Player.Run.ReadValue<float>();
}
if (crouching)
{
    currentSpeed = crouchSpeed;
    isRunning = false;
    transform.localScale = new Vector3(transform.localScale.x, crouchYScale, transform.localScale.z);
}
else // if move
{
    transform.localScale = new Vector3(transform.localScale.x, startYScale, transform.localScale.z);
}
controller.Move(movement * currentSpeed * Time.deltaTime); // without duplication and select true speed in last

CodePudding user response:

private void PlayerMovement()
    {
        // stuff
        controller.Move(movement * moveSpeed * Time.deltaTime);

        // stuff
        if (crouching)
        {
            // stuff
            controller.Move(movement * crouchSpeed * Time.deltaTime);
        }

you do normal movement, then you ALSO do movement based on your run/crouch state.

Consider instead setting a currentSpeed equal to your walk speed, go through your cases and set the currentSpeed as appropriate, and then only have one place where you actually .Move(), after your speed is set.

  • Related