0
\$\begingroup\$

I'm making a simple game and when the player crouches/slides I would want to make the character to change size. However when it changes to its smaller size it doesn't go back to its original size after you release the crouch button.

using UnityEngine;

public class advancedMovement : MonoBehaviour
{

    PlayerMovement basicMovementScript;
    public float sprint = 5f;
    public float slideSprint = 6f;
    public float deceleration = 0.5f;

    public CharacterController ccr_controller;
    public float ControllerHeight;

    // Start is called before the first frame update
    void Start()
    {
        basicMovementScript = GetComponent<PlayerMovement>();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftShift))
            basicMovementScript.speed += sprint;
        else if (Input.GetKeyUp(KeyCode.LeftShift))
            basicMovementScript.speed -= sprint;

        if (Input.GetKeyDown(KeyCode.LeftControl))
        {
            basicMovementScript.speed += slideSprint;
            ccr_controller.height = ControllerHeight;
            ControllerHeight = 7f;
        }

        if (Input.GetKeyUp(KeyCode.LeftControl))
        {
            basicMovementScript.speed -= slideSprint;
            ccr_controller.height = ControllerHeight;
            ControllerHeight = 14f;
        }
    }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The reason for your problem could be that you have just one variable ControllerHeight which gets both changed and used to restore the value of ccr_controller.height. This seems to cause a lot of confusion for you because you don't seem to always be aware of what value it has.

You might want to use two variables here with proper names:

  • float heightStand: The height the character has when standing. The value of this variable should never change during the game.
  • float heightCrouch: The height the character has when crouched. The value of this variable should also never change.

Use these two variables when you want to set the height of the character controller.

    if (Input.GetKeyDown(KeyCode.LeftControl))
    {
        basicMovementScript.speed += slideSprint;
        ccr_controller.height = heightCrouch;
    }

    if (Input.GetKeyUp(KeyCode.LeftControl))
    {
        basicMovementScript.speed -= slideSprint;
        ccr_controller.height = heightStand;
    }

When you have any situations where you need the current height of the character, use ccr_controller.height.

\$\endgroup\$
1
  • \$\begingroup\$ To me the actual issue seems to be that he is first assigning the old value and changes it to the actual wanted value afterwards. Totally agree that two const values remove the problem alltogether \$\endgroup\$
    – Zibelas
    Mar 11, 2021 at 9:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .