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

2014/10/10

Can u help me to update my health bar

coder04 coder04

2014/10/10

#
This is the code but it will not lose health when laser eats ship
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Enemylaser here.
 * 
 */
public class Enemylaser extends Mover

{
    private int life; 
    boolean fired;
    public Bar bar = new Bar("YourShip", "Health Points", 10, 10);
    /**
     * Act - do whatever the Enemylaser wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
     public void act()
     {
        move(20);
        eat();
        life--;
       if (life == 0)
       {  
           getWorld().removeObject(this);  
       }
       ifAtWorldEdge();
       if (fired==false) setRotation(Warship.rotation);
       if (fired==false) fired=true;
     }
       
    public void ifAtWorldEdge()  
    {  
        if (atWorldEdge())  
        {  
             getWorld().removeObject(this);  
        }  
    }  
     
     public void eat()
    {
        Actor Ship;
        Ship = getOneObjectAtOffset(0, 0, Ship.class);
        if (Ship != null)
        {
            World World;
            World = getWorld();
            GameOver gameover = new GameOver();
            //World.addObject(gameover, World.getWidth()/2, World.getHeight()/2);
            //World.removeObject(Ship);
            bar.add(-1);
        }  
    }
}   
    
    
danpost danpost

2014/10/10

#
It looks like you are creating a healthbar for the laser, which is not the same healthbar that you have in your Ship class. Remove line 12 and change line 50 to:
((Ship)Ship).bar.add(-1);
You should, however, refrain from using the same name of a class as a variable name. That is, you should use something like 'Actor ship;' instead of 'Actor Ship;'. I noticed that your 'life' field starts at zero and is decreased from there. It will never be checked and found to be zero (see lines 21 through 25) . Also after that (line 26),, you are using a method that requires the actor be in the world. If is was removed (line 24) you will throw an IllegalStateException.
You need to login to post a reply.