How do I use % again?

Non-platform specific questions.

How do I use % again?

Postby kevinphua » Mon Oct 12, 2020 2:31 pm

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?
kevinphua
 
Posts: 1
Joined: Tue Oct 06, 2020 5:24 pm
Score: 0 Give a positive score

Re: How do I use % again?

Postby lcl » Tue Oct 13, 2020 6:29 pm

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.
User avatar
lcl
 
Posts: 2339
Joined: Thu Mar 25, 2010 5:55 pm
Location: Finland
Score: 276 Give a positive score


Return to General

Who is online

Users browsing this forum: No registered users and 1 guest