Home > Software design >  Unity character doesn't stop sprinting
Unity character doesn't stop sprinting

Time:05-05

I only recently got into Unity, and I have made a character movement system; everything is working besides from sprinting. I have the user use "Left Shift" to sprint, although it seems sprinting never turns off. I'm not quite sure the reasoning as to why this happens or what part of code could be fixed to accommodate for this, as such, I have attached the source file of movement.

Here is the paste: https://pastebin.com/S1h5pEwq

In particular, this is the movement function:

void Movement()
    {
        Vector2 axis = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")) * walkSpeed;
        Vector3 forward = new Vector3(-Camera.main.transform.right.z, 0.0f, Camera.main.transform.right.x);
        Vector3 wishDirection = (forward * axis.x   Camera.main.transform.right * axis.y   Vector3.up * rb.velocity.y);
        rb.velocity = wishDirection;

        if (Input.GetKey(KeyCode.LeftShift))
        {
            isSprinting = true;
        }
        else
        {
            isSprinting = false;
        }

        if (isSprinting == true)
        {
            walkSpeed = 10.0f;
        }
    }

More specifically, my goal is to have Sprint be activated strictly while the key is pressed.

CodePudding user response:

Try this:

void Movement()
{
    Vector2 axis = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")) * walkSpeed;
    Vector3 forward = new Vector3(-Camera.main.transform.right.z, 0.0f, Camera.main.transform.right.x);
    Vector3 wishDirection = (forward * axis.x   Camera.main.transform.right * axis.y   Vector3.up * rb.velocity.y);
    rb.velocity = wishDirection;

    if (Input.GetKey(KeyCode.LeftShift))
    {
        isSprinting = true;
    }
    else
    {
        isSprinting = false;
    }

    if (isSprinting == true)
    {
        walkSpeed = 10.0f;
    }
    else
    {
       walkSpeed = 0.0f
    }

}

The problem in your script was that you were not resetting the speed.

CodePudding user response:

If(Input.GetKeyUp(KeyCode.LeftShift)){
isSprinting = false;
}

This will do, you didn't check when the player stopped pressing shift.

  • Related