Search Unity

How to make the player sprint using shift?

Discussion in 'Editor & General Support' started by Nathanaji01, Jun 18, 2019.

  1. Nathanaji01

    Nathanaji01

    Joined:
    Oct 8, 2017
    Posts:
    24
    Hi. I have made a movement script in which the player moves using the WASD keys. I want to make the player move faster/sprint when I hold shift. Currently, when I press shift the walking speed just increases by that sprint speed and does not go down. This is the code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Player : MonoBehaviour {
    6.  
    7.     private Rigidbody rb;
    8.     public int speed;
    9.     public int sprint;
    10.  
    11.     void Start ()
    12.     {
    13.         rb = GetComponent<Rigidbody>();
    14.     }
    15.  
    16.     void Update ()
    17.     {
    18.         if (Input.GetKeyDown(KeyCode.LeftShift))
    19.         {
    20.             speed = speed + sprint;
    21.         }
    22.         else
    23.         {
    24.             speed = speed;
    25.         }
    26.         float moveHorizontal = Input.GetAxis("Horizontal");
    27.         float moveVertical = Input.GetAxis("Vertical");
    28.  
    29.         Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    30.  
    31.         rb.AddForce (movement * speed);
    32.     }
    33. }
    34.  
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Your line 24 is silly. No need to assign a variable to itself. I'd do something like this:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Player : MonoBehaviour {
    6.  
    7.     private Rigidbody rb;
    8.     public int baseSpeed;
    9.     public int sprint;
    10.     private int currentSpeed;
    11.  
    12.     void Start ()
    13.     {
    14.         rb = GetComponent<Rigidbody>();
    15.     }
    16.  
    17.     void Update ()
    18.     {
    19.         if (Input.GetKey(KeyCode.LeftShift))
    20.         {
    21.             currentSpeed = baseSpeed + sprint;
    22.         }
    23.         else
    24.         {
    25.             currentSpeed = baseSpeed;
    26.         }
    27.         float moveHorizontal = Input.GetAxis("Horizontal");
    28.         float moveVertical = Input.GetAxis("Vertical");
    29.  
    30.         Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    31.  
    32.     }
    33.  
    34.     void FixedUpdate ()
    35.     {
    36.         rb.AddForce (movement * currentSpeed);
    37.     }
    38. }
    39.  
    Or I would use both GetKeyDown and GetKeyUp.

    Note that you shouldn't add forces in Update, or your frame rate will drastically affect the speed of your character. You should add forces in FixedUpdate (though you shouldn't take key input in FixedUpdate, you do that in Update).
     
    natethetank30 and Nathanaji01 like this.
  3. Nathanaji01

    Nathanaji01

    Joined:
    Oct 8, 2017
    Posts:
    24
    Thanks for this. But I am encountering another problem. When I have the "add force" line in the fixed update this error occurs: upload_2019-6-19_17-4-23.png
    Would you please help?
    Also, I wanted to add in a jump script into this script. Sorry if this is bothering you but it would be a great help.
     
    Last edited: Jun 19, 2019
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Yeah well I didn't test it. Just make "movement" part of the class instead of local scoped to Update.
     
  5. Nathanaji01

    Nathanaji01

    Joined:
    Oct 8, 2017
    Posts:
    24
    Hi, I didn't understand what you meant by this. Would you please explain? Sorry if this is bothering you. I am a beginner at unity/programming and if you could help that would be great.
     
  6. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Player : MonoBehaviour {
    6.  
    7.     private Rigidbody rb;
    8.     public int baseSpeed;
    9.     public int sprint;
    10.     private int currentSpeed;
    11.     private Vector3 movement = new Vector3(0f, 0f, 0f);
    12.  
    13.     void Start ()
    14.     {
    15.         rb = GetComponent<Rigidbody>();
    16.     }
    17.  
    18.     void Update ()
    19.     {
    20.         if (Input.GetKey(KeyCode.LeftShift))
    21.         {
    22.             currentSpeed = baseSpeed + sprint;
    23.         }
    24.         else
    25.         {
    26.             currentSpeed = baseSpeed;
    27.         }
    28.         float moveHorizontal = Input.GetAxis("Horizontal");
    29.         float moveVertical = Input.GetAxis("Vertical");
    30.  
    31.         movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    32.  
    33.     }
    34.  
    35.     void FixedUpdate ()
    36.     {
    37.         rb.AddForce (movement * currentSpeed);
    38.     }
    39. }
    40.  
     
    tdanut1994 likes this.
  7. GieroGames

    GieroGames

    Joined:
    Jan 2, 2021
    Posts:
    1
    this script yeets me in the air
     
  8. zedz

    zedz

    Joined:
    Aug 31, 2013
    Posts:
    255
    yeets me?
    if you're talking about the first script, I can see a major bug, when the person presses shift, they will just keep on accelerating, even when they stop sprinting they will still be sprinting
     
  9. W4uLi

    W4uLi

    Joined:
    Sep 7, 2016
    Posts:
    1
    It's been years since this was posted but maybe someone else finds this who needs a solution. You need to have a bool to check if the player is sprinting to prevent spamming the variable.
    Code (CSharp):
    1.    
    2. void PlayerSprint()
    3.  {
    4.     if (Input.GetKey(KeyCode.LeftShift)) // while player holds shift he can sprint
    5.     {
    6.         if(!isSprinting) /
    7.         {
    8.             currentSpeed += sprintSpeed;
    9.             isSprinting = true; // right after we apply the double speed or whatever, we set the bool to true so it can't do it over and over again.
    10.         }
    11.     }
    12.     if (Input.GetKeyUp(KeyCode.LeftShift)) // as soon as he lets go, the bool turns false and the speed is reset
    13.     {
    14.         currentSpeed = defaultSpeed;
    15.         isSprinting = false;
    16.     }
    17. }
    put it in Update and you should be fine.
     
    JustThinking likes this.
  10. boneholio

    boneholio

    Joined:
    Jan 2, 2023
    Posts:
    3
    maybe someone could help me out here - trying to append the extant third person camera / movement script i'm working on with scripts that add jump / sprint functions, eventually with animations attached (walking, sprinting, jumping, and idling)

    upload_2023-1-2_1-14-31.png

    but when i try to add this script to Player, i get this:

    upload_2023-1-2_1-15-18.png
     

    Attached Files:

  11. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Please don't necro-post. I have no idea how you named your script the title of a forum post, but just go back to the tutorial you're working on and work through it one step at a time, fix your mistakes.

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!


    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors, don't post here and DO NOT NECRO POST... just go fix your errors! Here's how:

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.