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

2021/3/23

HP decrementor within a superclass method

blossomburst blossomburst

2021/3/23

#
I'm trying to make a superclass method that gets passed a max HP value from a subclass calling the method from the act(), but the value keeps resetting each act() cycle. Is this an issue that needs instance variables instead of ones local to the method? Any help is appreciated.
// ***from super class
public void health(Integer HP) 
    {
        //health & removal of this
        Integer health = HP;
        boolean remove = false;//declare false by default
        Bullet b = (Bullet)getOneIntersectingObject(Bullet.class);//get Bullet actor
        Bomb bomb = (Bomb)getOneIntersectingObject(Bomb.class);//get Bullet actor
        
        if(b != null || bomb !=null){//when returns Bullet or Bomb...
            health--; //...decrement health counter by 1
        }
          //display health 
        if(health < 0) //health depleted
            remove = true;
        if(remove){//when either above condition is true
            getWorld().removeObject(this); //remove Target from World
        } 
        //display HP to test if it decrements w/o resetting
        getWorld().showText("DragonHealth: "+ health.toString(), 60, 100);
    }


//***from subclass (everything else is empty)
public void act()
    {
        health(75); //max HP value for subclass object
    } 
danpost danpost

2021/3/24

#
The act method is constantly being called. Change "void act()" to << Subclass Name >>"()".
blossomburst blossomburst

2021/3/24

#
I tried calling the method in the constructor, but it gives a runtime error in the world where the subclass appears.
java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed.
	
danpost danpost

2021/3/24

#
blossomburst wrote...
I tried calling the method in the constructor, but it gives a runtime error in the world where the subclass appears.
java.lang.IllegalStateException: Actor not in world. An attempt was made to use the actor's location while it is not in the world. Either it has not yet been inserted, or it has been removed.
Sorry -- I should have looked more closely, at first. Yes, health needs to be an instance variable in superclass:
public int health;
Put (only) the following line in constructor of subclass:
health = 75;
In above codes, remove line 5. Change line 2 to:
public void health()
and change line 27 to:
health();
blossomburst blossomburst

2021/3/25

#
It works, thank you.
You need to login to post a reply.