Search Unity

Sprinting Help (C#)

Discussion in 'Scripting' started by Steelshot, Jan 19, 2019.

  1. Steelshot

    Steelshot

    Joined:
    Feb 24, 2015
    Posts:
    102
    Code (CSharp):
    1.  
    2.         //Calculate our movement velocity/speed as a 3d vector
    3.         float xmove = Input.GetAxisRaw("Horizontal");
    4.         float zmove = Input.GetAxisRaw("Vertical");
    5.    
    6.         Vector3 movehorizontal = transform.right * xmove;
    7.         Vector3 movevertical = transform.forward * zmove;
    8.  
    9.         //final movement vector
    10.         Vector3 _velocity = (movehorizontal + movevertical).normalized * speed;
    11.         Vector3 _sprintvelocity = (movehorizontal + movevertical).normalized * (speed * 2);
    12.  
    13.         //Apply movement
    14.         motor.Move(_velocity);
    15.         if (Input.GetKeyDown(KeyCode.LeftShift))
    16.             motor.Move(_sprintvelocity);
    17.  
    I'm not so sure what's wrong with my code, I'm trying to multiply the speed variable twice to enable sprinting for the player. Is it something wrong with where the if function is placed? I'm just not sure.
     
  2. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
    I am not exactly sure where the issue is (because you didnt say what was wrong, intended vs actual effect) but I just tided the code a little, let me know if this works:

    Code (CSharp):
    1. float xmove = Input.GetAxisRaw("Horizontal");
    2. float zmove = Input.GetAxisRaw("Vertical");
    3.  
    4. Vector3 movehorizontal = transform.right * xmove;
    5. Vector3 movevertical = transform.forward * zmove;
    6.  
    7. // No point duplicating the calculation, just take the normal move
    8. // velocity and multiply it by your sprint speed
    9. Vector3 _velocity = (movehorizontal + movevertical).normalized * speed;
    10. Vector3 _sprintvelocity = _velocity * 2;
    11.  
    12. // Just to make this explicit, add an else
    13. if (Input.GetKeyDown(KeyCode.LeftShift))
    14.     motor.Move(_sprintvelocity);
    15. else
    16.     motor.Move(_velocity);
    17.  
     
  3. Steelshot

    Steelshot

    Joined:
    Feb 24, 2015
    Posts:
    102
    Sorry that I wasn't clear on the situation. I intended for the player to hold down left shift to sprint, but in reality, it didn't do anything when left shift was pressed. I tested out your code, but I had to make my code specifically like that so the camera can rotate up and down, instead of just left and right like your code does.