5
\$\begingroup\$

This code animates my main game sprite by increasing the animation frame. First I check if the character is moving, then I increase the animation counter until it reaches the desired speed, and then if so, I increase the animation frame.

How can I make it more elegant and optimised in terms of speed?

       if (moving){
        anispeed++;
        if (anispeed==animaxspeed){
            anispeed=0;
            animationframe++;
            if (animationframe==3) animationframe=0;
        }
\$\endgroup\$
  • \$\begingroup\$ quick question, why do you need to reset the anispeed when increasing the animationframe by one? I don't understand why you do this... Your posted code also misses the closing brace. !! \$\endgroup\$ – Vogel612 Apr 14 '14 at 7:08
  • \$\begingroup\$ Anispeed is used as a counter, when it hits animaxspeed then we change the animation to the next frame. Otherwise the animation is as fast as the computer can go. \$\endgroup\$ – Munkybunky Apr 14 '14 at 17:58
7
\$\begingroup\$

Two small comments:

Naming:
The convention for variable names in Java is camelCase. Your animationframe should instead be animationFrame when going by that rule. Similar for your animaxspeed. You don't have to save characters in your code, write it out: animationMaxSpeed.
anispeed can also be written out: animationSpeed. This should make your code even more clear than it is ;)

Braces:
It's also convention to place all if-blocks in braces, disregarding whether they have to, or not. This is to decrease the possibility of bugs when changing such blocks and forgetting braces.

if (animationFrame == 3) {
    animationFrame = 0;
}

Also the Java-Coding-Standard is 4 spaces indentation. It might be, that the markup for SE broke yours, but either way, your first if-statement is too far in.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.