Is there any downside to my implimentation of an attack throttle?

Hello,

I implemented a throttle a little bit differently and was wondering if my way has any downsides. One way I believe my implementation is better is that in my case, we only calculate the new time once ever attack instead of once every frame, which I think is much more efficient. Am I missing something that makes my code inferior to Sam’s or a reason I should use Sam’s so that it will work better with the game further down the course? I just have a float that starts at 0, then every time we attack, it sets this float to the current time + the interval to wait.

My Code:

[SerializeField] float attackInterval = 1f;
float nextAttackTime = 0;

private void AttackBehavior()
{
if (Time.time > nextAttackTime)
{
myAnimator.SetTrigger(“attack”);
nextAttackTime = Time.time + attackInterval;
}
}


Sam's:

[SerializeField] float timeBetweenAttacks = 1f;
float timeSinceLastAttack = 0;

private void Update()
{
timeSinceLastAttack += Time.deltaTime;
}

private void AttackBehaviour()
{
GetComponent().SetTrigger(“attack”);
if (timeSinceLastAttack > timeBetweenAttacks)
{
GetComponent().SetTrigger(“attack”);
timeSinceLastAttack = 0;
}
}

Sam has a lecture explaining (actually demonstrating the pitfalls of) using absolute time references instead of simple timers…

Note that you may need to join the free course https://www.gamedev.tv/p/extra?coupon=1D3ABAD8 to view this lecture.

The core of the explaination deals with the resolution of floating point numbers… while something may appear to work absolutely fine early in the game, as Time.time increases, the floating point math begins to lose resolution, to the point where 1 second is statistically insignificant and adds nothing to the number.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.