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

2017/2/26

each object has a own counter

Telko Telko

2017/2/26

#
Hi guys, Im struggling to make it so that an object with an image (in my project its a base for minions) has at the same time a counter showing the amount of minions stored in the base. It is important that the construction call is in the base class,because there will be several bases in my world but i dont know how to have parralel images (the one of the base and the counter) at the same time. Does anyone know a solution? Thanks a lot
danpost danpost

2017/2/26

#
It is easier to deal with one actor with a changing image than with two actor, having one with a changing image, and needing to deal with interaction between the two. You can accomplish this by keeping a reference to an image without any text and an 'update' method to apply the text on the image to be shown:
// instance fields
private GreenfootImage baseImg; // reference to non-changing part of image
private int minions = 10; // number of minions (set to initial value)


// in constructor
GreenfootImage img = getImage();
baseImg = new GreenfootImage(img.getWidth(), img.getHeight()+24); // increased image size (taller)
baseImg.drawImage(getImage(), 0, 0); // same image with extra space below
updateImage(); // set initial image

// the updateImage method
private void updateImage()
{
    setImage(new GreenfootImage(baseImg); // set new base image without text
    GreenfootImage textImg = new GreenfootImage(""+minions, 24, null, null); // the text image to apply
    getImage().drawImage(textImg, ((getImage().getWidth()-textImg.getWidth())/2, getImage().getHeight()-24); // applying text
}
Then, at any point in the code where the number of minions changes, call this method.
You need to login to post a reply.