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

2016/9/22

Non static method (getHealthBar)

MaxAaldering MaxAaldering

2016/9/22

#
I was trying to get a healthbar on greenfoot but i cant find out whats the error in my code
 public void hitMouse()
    {
        Actor Mouse = getOneIntersectingObject(Mouse.class);
        if (Mouse !=null)
        {
            World myWorld = getWorld();
            MyWorld myworld = (MyWorld) myWorld;
            HealthBar healthbar = MyWorld.getHealthBar();

            if (touchingMouse == true )
            {
                health--;
                touchingMouse = true;
                

                if (healthbar.getHealth() <=0)
                {
                    getWorld().removeObject(this);
                }
            }
        }
    }
this is the code elephant and this is the code in MyWorld public class MyWorld extends World { HealthBar healthbar = new HealthBar(); /** * Constructor for objects of class MyWorld. * */ public MyWorld() { super(1000, 800, 1); populateWorld(); } public HealthBar getHealthBar() { return healthbar; } public void populateWorld() { addObject(new elephant(), 300, 300); addObject(new HealthBar(),100,40); addObject(new Mouse(), 90, 70); addObject(new Mouse(), 390, 200); addObject(new Mouse(), 360, 500); } }
Super_Hippo Super_Hippo

2016/9/22

#
You wrote the class name 'MyWorld' instead of the variable 'myworld' which you created the line before.
danpost danpost

2016/9/22

#
Another issue is that you are creating a second HealthBar object in the 'populateWorld' method. This one is being added into the world; but, the one in the 'healthbar' field is not. Just make the following change:
// change
addObject(new HealthBar(),100,40);
// to this
addObject(healthbar,100,40);
so that the one reference by the field is added into the world.
MaxAaldering MaxAaldering

2016/9/23

#
@danpost if i remove "new" from new healthbar it gets an error saying connot find symbol.
MaxAaldering MaxAaldering

2016/9/23

#
MyWorld.getHealthBar(); is also an error
Super_Hippo Super_Hippo

2016/9/23

#
Java is case sensitive. Danpost didn't only remove the 'new'. And as I already said, you have to use 'myworld' instead of 'MyWorld' or you just use this line as line 16 and remove lines 6 through 8:
if (((Healthbar)((MyWorld) getWorld()).getHealthbar()).getHealth() <= 0)
You need to login to post a reply.