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

2018/4/25

Need help with timer

Cmo Cmo

2018/4/25

#
want a 60 seconds timer. i want it to show how much time i have left plz help
 private int timer = 0;
    /**
     * Constructor for objects of class ShooterWorld.
     * 
     */
    public ShooterWorld()
    {
        super(600, 400, 1); 
        addObject(new Launcher(),300,375);
        addObject (new Plane(),100,30);
        prepare();

    }

    /**
     * Prepare the world for the start of the program.
     * That is: create the initial objects and add them to the world.
     */
    private void prepare()
    {

    }
    public void timer()
    {
        timer--;
        showtimer();
        if (timer>0)
        {
            timer--;
            if(timer == 0) 
            Greenfoot.stop();
        }
    }

    public void showtimer()
    {
        showText("Time:" + timer, 625, 30);    
    }
}
Spazzy Spazzy

2018/4/25

#
I could also use some help with this code. Anyone know how to or have any helpful tips?
danpost danpost

2018/4/25

#
The first line says that the timer field should count down from zero. No wonder it does not work. Also, in your timer method, why would you want to possibly subtract two from the timer field in one act step? Change the timer method to this:
public void timer()
{
    if (timer > 0)
    {
        timer--;
        showtimer();
        if (timer == 0) Greenfoot.stop();
    }
}
You probably also want to change how the showTimer method displays the timer field value, maybe using something like this:
showText("Time:"+(timer/60), 625, 30);
Yehuda Yehuda

2018/4/25

#
You would also need to call the 'timer' method from inside an act method for it to be executed.
danpost danpost

2018/4/26

#
Yehuda wrote...
You would also need to call the 'timer' method from inside an act method for it to be executed.
Touché.
Cmo Cmo

2018/4/26

#
Thank you! danpost senpai
You need to login to post a reply.