I’m following a tutorial, and the instructor kind of glazes over this part ( as if I should know already ), but I’m having a little bit of trouble understanding the statement. So, for context
This is initiated from the Update method
if (damageDelayCount > 0)
In the method we have, which obviously decrements damageDelayCount over time
damageDelayCount -= Time.deltaTime;
then later we have
if (Mathf.Round(damageDelayCount * 10) % 2 == 0)
// Do stuff
I know it’s related to the countdown, so that when we hit 0 it does ‘do stuff’ part of the code, however, having a little trouble understanding the * 10 ) % 2 portion of the code, I kind of know what it’s doing, but would like a simple English explanation of exactly what it’s doing, just so I can add in my own comment in the code to understand it at a later date. ( ?Multiplying by 10 to make it easier to use the Mathf.Round function when counting down? )
BTW, I’ve already repurposed the logic to be ( because vs doesn’t like the == 0 comparision )
if (Mathf.Approximately(Mathf.Round(damageDelayCount * 10) % 2, 0))
// Do Stuff
Hi @ ,
Looks somewhat convoluted to my eye. But, If you print out the results of that calculation, it looks like it could be just used to add a sort of random behavior so that the code stays compact. Sometimes it might be 1-5 updates before the modulo operation value is 0. And you are right, when the damageDelayCount is multiplied by 10, it’s to get a bigger number that is a value in some range, depening on the input. Anyway just do a few debug prints (print the delay, rounded value, and the modulo result) and you will see quickly how that logic exactly works.
The % is called the remainder operator, it divides the first number by the second and returns the remainder of the calculation. So, 5 % 2 would return 1, 4 % 2 would return 0.
Basically, in your example, the statement is checking if the rounded value you supply (Mathf.Round(damageDelayCount * 10) is a multitude of 2.
@Team2Studio it’s more commonly called modulo operation. That’s what it is called in C#, and same goes for HLSL and many other languages. It does find the remainder but it’s not called remainder operator.
Thanks for the replies, that makes much more sense now. For some reason, I had divide by 2 in my mind, hence the confusion, but the remainder operator makes much more sense.
Kind Regards
BTW : The full code is used to ‘flash’ an object a set number of times before the damageDelayCount reaches 0, also, during which time the Player is unable to be damaged again.