Energy System for Sprinting

How to create a Stamina System for Sprinting

Tristan Engel
2 min readJun 7, 2021

--

In this article we create an energy system for our ‘sprint’ function to prevent the player to move fast indefinitely.

In the image below watch the values go up and down in the Inspector and how boost is used by the player.

Pseudocode

Roughly put the logic would be:

If player uses sprint
then decrease energy
If sprint isn’t used
then increase energy
If energy is zero or less
then stop sprinting

We also added that the player can not activate sprint when current energy is below 3.
Important is to check is whether sprint is active or not when it has to be stopped. When energy is zero or less or GetButtonUp. If this is not done Player speed will be decreased twice every time the energy value gets to zero and the key gets released.

Actual Code

Result of the translating the pseudo code:
(rhe VFX code can be omitted)

Selectable code

//Sprint with Energy System
if (_energyCurrent < 0 || Input.GetButtonUp("Fire3"))
{
if (_energyCurrent < 0)
{
_energyCurrent = 0;
}
if (_isSprint == true)
{
_isSprint = false;
_speed /= _sprintModifier;
//vfx
_thruster.transform.localScale -= _scaleChange;
_thruster.transform.position -= _posChange;
}
}
else if (_energyCurrent > 3 && Input.GetButtonDown("Fire3"))
{
_isSprint = true;
_speed *= _sprintModifier;
//vfx
_thruster.transform.localScale += _scaleChange;
_thruster.transform.position += _posChange;
}
if (_isSprint == true)
{
//drain energy
_energyCurrent -= _sprintStaminaCost * Time.deltaTime;
}
else if (_isSprint == false)
{
if (_energyCurrent >= _energyMax)
{
_energyCurrent = _energyMax;
}
else
{
//recharge energy
_energyCurrent += _energyCharge * Time.deltaTime;
}
}

--

--

Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.