Home > Back-end >  How to make my player move faster/sprint when I hold down the shift key? Unity
How to make my player move faster/sprint when I hold down the shift key? Unity

Time:01-22

so i tried to make my player move faster/make him sprint (it's in first person btw) put it doesn't really work.I wrote the code and everytime a press shift/hold the sprint speed just stacks and when i "walk" im not "walking" im just moving extremely fast.

Here's the entire code: `using System.Collections; using System.Collections.Generic; using UnityEngine;

public class PlayerMovement : MonoBehaviour { public CharacterController controller;

public float walkSpeed = 10f;
public bool isSprinting;
public float sprintMultiplier;
public float gravity = -9.81f;
public float jump = 1f;

public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;

Vector3 velocity;
bool isGrounded;

// Update is called once per frame
void Update()
{
    isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

    if (isGrounded && velocity.y < 0)
    {
        velocity.y = -2f;
    }

    //Moving
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");

    Vector3 move = transform.right * x   transform.forward * z;

    controller.Move(move * walkSpeed * Time.deltaTime);

    //Jumping
    if (Input.GetButtonDown("Jump") && isGrounded)
    {
        velocity.y = Mathf.Sqrt(jump * -2f * gravity);
    }

    velocity.y  = gravity * Time.deltaTime;

    controller.Move(velocity * Time.deltaTime);

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

    if (isSprinting == true)
    {
        walkSpeed  = sprintMultiplier;
    }
}    
    

}`

i follwed a bunch of other tutorials but none of them work. If anybody knows how to fix this or make it work please comment:)

CodePudding user response:

This is where the problem is..

if (isSprinting == true)
{
    walkSpeed  = sprintMultiplier;
}

Every frame in which isSprinting is true, walkspeed is increased, but it never decreases.

You could add some more variables like these...

public float normalSpeed = 10f;
public float sprintSpeed = 20f;

and change your code to this...

if (isSprinting == true)
{
    walkSpeed = sprintSpeed;
}
else
{
    walkSpeed = normalSpeed;
}

So walkspeed is the variable that dictates how fast your player moves, and when they're walking it's set to normalSpeed, and when they're sprinting it's set to sprintSpeed.

  • Related