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

2021/6/19

How to addObject in constructor of an actor class

Nicole05 Nicole05

2021/6/19

#
I was wondering if it was possible to add an object to the world if the Building constructor has been called into a world. I would like to know if you can get the X and Y value of the Building in the world if it was called.
1
2
3
4
5
6
7
8
9
private StatBar healthBar = new StatBar(100, currentHp, null, 100, 10,0, Color.GREEN, Color.RED, false, Color.WHITE, 1);
 
public Building(){       
    World world = getWorld();
    image = drawBuilding();
    setImage (image);
    world.addObject(healthBar, (Building.class).getX(), getY() - 50);
     
}
RcCookie RcCookie

2021/6/19

#
The problem is that when the object is created it is not in a world yet. So, it has to add itself to the world first, then it can add other objects. These information have to be passed into the constructor.
1
2
3
4
5
public Building(World world, int x, int y) {
    world.addObject(this, x, y);
    world.addObject(healthBar, x, y - 50);
    // Some other stuff
}
By doing so you can also replace this
1
2
Building building = new Building();
addObject(building, someX, someY);
with this
1
new Building(this, someX, someY);
You need to login to post a reply.