by DST » Tue Jun 28, 2011 2:29 pm
If isn't so bad, really. Computers were designed to do it lots of times every second.
But the real way to avoid if is to manage the resource flow. The more things fall into place on their own, or are queried in a sensible chain, the fewer if's you need.
One example would be on an rts game, instead of asking each unit 'what are you doing?', it would make the most sense to first ask it 'are you doing nothing?' Because when the answer is no, you don't have to ask any more questions to that unit for a while, and that's probably the most common answer....
And when using case switches, you can automate the process of determining the state of the switch. When events happen, the state gets switched. The more things you control with the switch, the fewer if's. For instance you may have a 5 case switch with if's inside of it, but couldn't you add some of those if's to the switch and have 8 cases? Sometimes switching a state even when the variable controlling the state doesn't need switched won't harm the switch and answers more questions about that actor.
Lastly, using equations to determine something can help.
if(x>0){
xvelocity=-1;}
else{
xvelocity=1;}
or
xvelocity=(-x/x);
produce the same result. (of course the second one won't account for 0's....there are always other things to work around. If it's a createactor script, simply don't spawn them at 0...).
But ifs will always remain a fundamental part of programming. Just keep them manageable.