FPSController Example Explained

This system uses the default Unity Standard Assets FPS Controller as an example of how you can control the stamina, but this could be converted to use with your own controller.

Making the player character Jump:

  • On Line 120 of the "FirstPersonControllerCustom" script you will find this code below, this could calls the "StaminaJump" mothod from the "SurvivalVitalsManager" and checks whether stamina is above 20% of the remaining stamina.

if (m_Jump)
{
     SurvivalVitalsManager.instance.StaminaJump();
}
  • The outcome is below:

public void StaminaJump()
{
   if(playerStamina >= maxStamina * 20 / 100)
   {
       player.PlayerJump();
       playerStamina -= jumpCost;
       UpdateAllVitalUI();
   }
}
  • On line 135 you will find I moved the "PlayerJump" method in the FPSController script to make sure it could be used and called from the "VitalsManager".

This is inside the "FirstPersonControllerCustom" script
public void PlayerJump()
{
     m_MoveDir.y = m_JumpSpeed;
     PlayJumpSound();
     m_Jump = false;
     m_Jumping = true;
}

Detecting if we're sprinting

  • Line 223 of the "FPSController" script we're checking to see if the player is walking or not, if the player is then the SprintDetection() method is called and we pass false.

if (m_IsWalking)
{
    SurvivalVitalsManager.instance.SprintDetection(false);
}
  • Line 229 of the FPSConroller script, you can see we're checking to see if we're not walking (So we would be sprinting) and character velocity is greater than 0. We then call the MoveDetection() method.

if (!m_IsWalking && m_CharacterController.velocity.sqrMagnitude > 0)
{
      SurvivalVitalsManager.instance.MoveDetection();
}
  • Inside the VitalsManager you can see the MoveDetection method calls the sprinting method to decrease stamina as we're making sure we're above 0 stamina, if we are sprint. If not, set isWalking to true, so it stops the controller from sprinting.

public void MoveDetection()
{
   if (playerStamina > 0)
   {
      weAreSprinting = true;
      Sprinting();
   }
   else
   {
      player.m_IsWalking = true;
    }
}

Last updated