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

2017/5/10

My Health Bar doesn't work.

Zaya_Neal Zaya_Neal

2017/5/10

#
Everything is compiled and in theory, should work but it doesn't. Can anyone help me? public class Player extends Actor { boolean touchingEnemy = false; /** * Act - do whatever the Player wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(5); hitEnemy(); } public void hitEnemy() { Actor enemy = getOneIntersectingObject(Enemy.class); if(enemy != null) { World myWorld = getWorld(); Earth earth = (Earth)myWorld; HealthBar healthbar = earth.getHealthBar(); if(touchingEnemy == false) { healthbar.loseHealth(); touchingEnemy = true; if(healthbar.health <=0) { myWorld.removeObject(this); } } } else { touchingEnemy = false; } } }
danpost danpost

2017/5/10

#
Please show your world class code (so that we can see how your are handling the HealthBar there). Use code tags around your code to make it easier to refer to your code (see the 'Posting code? read this!' link below the reply box).
Zaya_Neal Zaya_Neal

2017/5/11

#
public class Earth extends World
{
    HealthBar healthBar = new HealthBar();
    /**
     * Constructor for objects of class MyWorld.
     * 
     */
    public Earth()
    {    

        super(600, 400, 1); 

        prepare();
    }
    public HealthBar getHealthBar()
    
    {
        return healthBar;
    }
    
    /**
     * Prepare the world for the start of the program.
     * That is: create the initial objects and add them to the world.
     */
    private void prepare()
    {
        HealthBar healthbar = new HealthBar();
        addObject(healthbar,62,31);
        healthbar.setLocation(55,23);
        Player player = new Player();
        addObject(player,132,229);
        Enemy enemy = new Enemy();
        addObject(enemy,272,228);
    }
}
danpost danpost

2017/5/11

#
Remove line 27. You already created a health bar at line 3 and assigned it to the 'healthbar' field. Line 27 declares a local variable with the same name as the field and assigns a different health bar to it (not to the field on line 3). Since this is the health bar added into the world, any changes to the one referenced at line 3 (which is the one the 'getter' method returns in lines 15 through 19), will not be seen. Those changes are being made, however.
Zaya_Neal Zaya_Neal

2017/5/11

#
It worked! Thank you danpost!
SR20 SR20

2017/5/11

#
No Worries
No Worries
You need to login to post a reply.