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

2015/6/22

Getting the coordinates of one of many of the same actor

ChiveTheLizard ChiveTheLizard

2015/6/22

#
In my scenario there are many actors in play which are the same, however I need to coordinates of each one individually to make something follow each one of them. Is there any way i can do this within Greenfoot? Example: There are a lot of enemies that each need there own health bars to follow them and change individually.
Super_Hippo Super_Hippo

2015/6/22

#
When adding an enemy to the world, this enemy can add its health bar to the world. You can save this health bar object and let it move relative to the enemy. The health bar object doesn't need an act method. (This isn't full code, some methods are missing, but you will get the idea, I hope.)
//Enemy class
private HealthBar hb;
private int life, damage, speed;

//initialize fields
public Enemy(int type)
{
    switch(type)
    {
        case 0: life = 50; damage = 4; speed = 3; break;
        case 1: life = 200; damage = 3; speed = 2; break;
    }
}

//when being added, add the own health bar
protected void addedToWorld(World w)
{
    hb = new HealthBar();
    w.addObject(hb, getX(), getY()-10);
}

public void act()
{
    //...

    //set the health bar to the right position
    hb.setLocation(getX(), getY()-10);
}

//when losing health
public void loseHealth(int dmg)
{
    //or other names
    life -= dmg;
    hb.loseHealth(dmg);
}

//when removing the enemy (instead of removeObject)
public void remove()
{
    getWorld().removeObject(hb);
    getWorld().removeObject(this);
}
You need to login to post a reply.