This site requires JavaScript, please enable it in your browser!
Greenfoot back
Hundmat
Hundmat wrote ...

2019/11/15

Animation

Hundmat Hundmat

2019/11/15

#
I have seen several ways to animate images in greenfoot, but which is the most convenient way of coding it. Right now I'm using this
    GreenfootImage[] Idle ={new GreenfootImage("Idle1.png"),new GreenfootImage("Idle2.png"),new GreenfootImage("Idle3.png"),new GreenfootImage("Idle4.png"), new GreenfootImage("Idle5.png"), new GreenfootImage("Idle6.png"),new GreenfootImage("Idle7.png"),new GreenfootImage("Idle8.png"),new GreenfootImage("Idle9.png"),new GreenfootImage("Idle10.png")};

double animationIndex = 0;

public void act() 
    {   setImage(Idle[(int)animationIndex]);


        animationIndex+=0.2;
        animationIndex %= 10;'

 }
danpost danpost

2019/11/15

#
Hundmat wrote...
I have seen several ways to animate images in greenfoot, but which is the most convenient way of coding it. Right now I'm using this << Code Omitted >>
Convenient? ... probably what you have is most convenient for you. However, convenient is not necessarily best. Use of the array is an excellent choice. Using a double value for an integer index does not seem appropriate. In fact, it is not possible for a computer to store the value of one-fifth exactly. And, although it may seem like a moot point, computations using double values takes longer than when using int values. Another thing that may help with regard to CPU usage is to only set an image when it changes. Setting an image, even the same image, every act cycles is something that can be avoided. I would probably use something like the following:
GreenfootImage[] Idle =
{
    new GreenfootImage("Idle1.png"), new GreenfootImage("Idle2.png"),
    new GreenfootImage("Idle3.png"), new GreenfootImage("Idle4.png"),
    new GreenfootImage("Idle5.png"), new GreenfootImage("Idle6.png"),
    new GreenfootImage("Idle7.png"), new GreenfootImage("Idle8.png"),
    new GreenfootImage("Idle9.png"), new GreenfootImage("Idle10.png")
};
int animationIndex;

public void act()
{
    animationIndex = (animationIndex+1)%50;
    if (animationIndex%5 == 0) setImage(Idle[animationIndex/5]);
}
You need to login to post a reply.