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

2016/10/10

Animation doesn't work and no syntax error.

Gold_Leader Gold_Leader

2016/10/10

#
Okay, here is my problem. This is the backdrop for my game. I set two images in my code that are the same image but just flipped. So it could give the illusion that it is snowing. I got the idea for this counter animate method from the Robot Tutorial in Oracle. My Code says there are no syntax errors and I've asked my instructor if he knew what the problem was. Help would once more be much appreciated :)
public class MyWorld extends World
{
    private GreenfootImage sky1 = new GreenfootImage("sky.png");
    private GreenfootImage sky2 = new GreenfootImage("sky2.png");
    int counter=0;
    /**
     * Constructor for objects of class MyWorld.
     * 
     */
    public MyWorld()
    {    
        super(582, 400, 1);        
        
        
        addObject(new mound(), 291,266);
        addObject(new sign(), 306,62);
        addObject(new Penguin(), 307,268);
        animate();
    }
    
    public void animate() {
        if(counter < 100){
        if (getBackground() == sky1){
            setBackground(sky2);  
            
            }
        else {
            setBackground(sky1);                 
        }  
        if (counter>100){
            counter =0;
        }                    
        
          
        counter++;
    }
}
}
danpost danpost

2016/10/10

#
The constructor, the block of code from lines 10 through 19, is only executed once, when the World object is created (which is when you compile or reset the project). So, calling 'animate' there only sets the initial image for the background. To continuously animate the background while the project is running, you need to call the method from a method that is repeatedly called. Greenfoot internally calls the an 'act' method for all actors in the active world and the 'act' method of that active World object which is supplied by the World class. Just like in your subclasses of Actor, you can override the 'act' method of the World class. Add to your MyWorld class the following:
public void act()
{
    animate();
}
This will not, in itself, fix your problem as you have several issues with the code in the 'animate' method. The way it is written the image try to change every act cycle minus one in every 101 acts. This is much faster than the eye can visualize and would be a flickering image. Making the image change every 3 or 4 acts should be sufficient:
public void animate()
{
    counter = (++counter)%6; // counter goes from 0 to 5, then repeats
    if (counter%3 == 1) // if '1' or '4'
    {
        if (counter/3 == 0) setBackground(sky1); else setBackground(sky2);
    }
}
You need to login to post a reply.