0

My Project is a First Person Jump&Run, I want my Player to Sprint by pressing Horizonzal or Vertical combined with Shift.

I already made a new Input, called Sprint, with negative Button "left shift"

My Player does normal move, but he doesn't Sprint.

Thanks a lot.

public class PlayerMovement : MonoBehaviour
{

public CharacterController controller;

public float speed = 12f;
public float sprint;

public float gravity = -9.81f;
public float jumpHeight = 3f;

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;

    }

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

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

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

    if (Input.GetButtonDown("Jump") && isGrounded)
    {

        velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);

    }

    velocity.y += gravity * Time.deltaTime;

    controller.Move(velocity * Time.deltaTime);

    // Noch nicht fertig -> Noch ausstehend
    if (Input.GetButtonDown("Horizontal") && Input.GetButtonDown("Sprint") || Input.GetButtonDown("Vertical") && Input.GetButtonDown("Sprint"))
    {
        controller.Move(move * (speed + sprint) * Time.deltaTime);

    }
}

1 Answers1

1

There are most likely problems with how the Input is being handled. My assumption is that GetButtonDown only returns true for the single frame when you press shift down. Use GetKey instead:

Input.GetKey(KeyCode.LeftShift)

If that doesn't work, try those 2 instead:

Input.GetKeyDown("left shift")

Input.GetKeyDown(KeyCode.LeftShift)

But there might be the same problem with those 2 as with "GetButtonDown".

Also, I think it'd help people understand your code better if you use english comments instead of german. I'm able to read it but most probably don't. Don't worry though, that also happened to me!

  • Your assumption is correct. GetKeyDown is when the key is pressed down (Only called once) | GetKeyUp is when the key is let go of (Only called once) | GetKey is repeated aslong as the key is held down – Legendary_zotar Jan 23 '21 at 19:12