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

2018/6/11

Trying to update a timer

jstadtherr jstadtherr

2018/6/11

#
I am getting the error that it doesn't recognize the variable timerText in act(), but it works in prepare()? any suggestions?
(in prepare())

        Text timerText = new Text();
        addObject(timerText,80,558);
        timerText.setText("Time left: " + (timer/60));
public class MyWorld extends World
{
    private int timer = 1800;
    public MyWorld()
    {
        super(1000, 600, 1); 
        prepare();
        act();
    }
    public void act()
    {
        if (timer>0){
            timer--;
            if (timer%60==0) timerText.setText("Time left: " + (timer/60));
            if (timer == 0) Greenfoot.setWorld(new TitleWorld());
        }
    }
Yehuda Yehuda

2018/6/11

#
That's because you initialize it in the prepare method (line 3 above). Since you initialized it inside a method another method cannot access it. (It would be easier if you posted the full class not different pieces.)
jstadtherr jstadtherr

2018/6/12

#
Thank you! I initialized it it act and it is working now, but for some reason when it gets into the single digits it puts a parentheses after the number for example it prints 7) instead of just 7, do you know why this is?
    public void act()
    {
        if (timer>0){
            timer--;
            Text timerText = new Text();
            addObject(timerText,80,558);
            if (timer%60==0)timerText.setText("Time left: " + (timer/60));
            if (timer == 0) Greenfoot.setWorld(new TitleWorld());
        }
    }
danpost danpost

2018/6/12

#
jstadtherr wrote...
Thank you! I initialized it it act and it is working now, but for some reason when it gets into the single digits it puts a parentheses after the number for example it prints 7) instead of just 7, do you know why this is? << Code Omitted >>
You will probably experience some lag as the timer runs longer. By creating a new Text object every act cycle, you world will be struggling to smoothly maintain all its objects. Create just one Text object outside the method, override the addedToWorld method to add the Text object into the world and continuously set its display every second.
You need to login to post a reply.