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

2017/6/5

Health Bar

ali18 ali18

2017/6/5

#
Hello, I need help, I need my playerBoat to lose a life after hitting a rock. However, at the moment, when I hit a rock my playerBoat disappears and is removed from the world. I have shown the coding I have sued below. I honestly have no idea what I'm doing wrong. This is the coding for my Rock
public void act() 
    {
        move();
        atWorldEdge();
        
            if (isTouching(PlayerBoat.class))
               {
               removeTouching(PlayerBoat.class);
               HealthBar hb = (HealthBar) getWorld().getObjects(HealthBar.class).get(0);
               hb.loseHealth();
               if (hb.health == 0)
               {
                getWorld().addObject(new GameOver(), getWorld().getWidth()/2, getWorld().getHeight()/2);
                
                
        
            }
    }
          
}
This is the code for my Health Bar
{
    int health = 3;
    int healthBarWidth = 150;
    int healthBarHeight = 15;
    int pixelsPerHealthPoint = (int)healthBarWidth/health;
    /**
     * Act - do whatever the HealthBar wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        update();
        //Lose of Health
    }    
    public HealthBar()
    {
        update();
    }
    public void update()
    {
        setImage(new GreenfootImage(healthBarWidth + 2, healthBarHeight + 2));
        GreenfootImage myImage = getImage();
        myImage.setColor(Color.WHITE);
        myImage.drawRect(0, 0, healthBarWidth + 1, healthBarHeight +1);
        myImage.setColor(Color.RED);
        myImage.fillRect(1, 1, health*pixelsPerHealthPoint, healthBarHeight);
    }
    public void loseHealth()
    {
        health--;
    }
}
Super_Hippo Super_Hippo

2017/6/5

#
The code is saying "if the rock is touching the boat, remove the boat". Exactly that is what is happening. I am not sure if the rock should move at all, but maybe you should remove the rock and not the boat. Usually, I would say the boat touches the rock and not the other way around, so you could place the code in your boat class and check for intersections with rocks.
You need to login to post a reply.