简体   繁体   中英

Unity character doesn't stop sprinting

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM