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

2021/4/1

Save world variable in actor class

hernry2812 hernry2812

2021/4/1

#
timeElapsed is a static int of my RaceWorld. To implement a lap counter, I woud like to save it every time my car hits the startline. My problem in this case is that I can't save the time of RaceWorld as a new int. I would like to know how to save a static int of world in an actor class as a new int. The timeElapsed static int in RaceWorld counts up, that works. I know that you could just put RaceWorld.timeElapsed instead of the time integer into the show Text method, but I would like to save certain times so I have to save it in a new integer of my cars class. In this case the showText method just shows that the time saving in int time doesn't work.
public class Car extends SmoothMover
{
    int lap1;
    int lap2;
    int lap3;
    int time = RaceWorld.timeElapsed;

    public void act() 
    {
        String showTime = time +"()()()";
        getWorld().showText(showTime, 300, 300);
    }
}
RcCookie RcCookie

2021/4/1

#
Since int‘s are a primitive type in Java, this ain‘t work. You will have to assign it every time you want to access it. The alternative (but unnecessarily complex) solution would be a wrapper class for the time int, for example:
public class RaceTime {
    public int time;
}

// In RaceWorld
RaceTime time = new RaceTime();
// For reassigning
time.time = someNumber;

// In Car
RaceTime time = RaceWorld.time;
// To use it
int currentTime = time.time;
But as I code this I realize that this is not any better, it just replaces RaceWorld with time. Also you could make a simple method for this:
// In Car
public int time() {
    return RaceWorld.time;
}
// To access it
int currentTime = time();
This is at least a little shorter…
danpost danpost

2021/4/1

#
Make line 6:
int time;
and start act with:
time = RaceWorld.timeElapsed;
hernry2812 hernry2812

2021/4/1

#
Thank you, I'll have a look at it!
You need to login to post a reply.