Page 1 of 1

How do I use % again?

PostPosted: Mon Oct 12, 2020 2:31 pm
by kevinphua
Alright, so recently for some reason I'm unable to be satisfied with just any code. It seems like it has to be small and efficient as possible. My current goal is to add something by 1 ever 5 or 10 frames, I think theres a way to do this in 1 line using % symbol. how?

Re: How do I use % again?

PostPosted: Tue Oct 13, 2020 6:29 pm
by lcl
Using the % operator gives the remainder of division. So, 10 % 3 gives 1, as that's what's left over from integer division of 10 by 3. When you want something to happen every 5 frames, check if frame % 5 is 0. That means there was no remainder.

Code: Select all
if (frame % 5 == 0)
    myVariable++;


Or, as a one-liner:
Code: Select all
myVariable += (frame % 5 == 0);


I think the first version is easier to read. The two should also be pretty much equal in terms of efficiency as there's a division and comparison being made in both versions.