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

2013/2/28

return value for bar image

AD12 AD12

2013/2/28

#
I'm trying to program a bar which should decrease when an object of another class is shooting. Here's my code to shoot:
public class Ship extends Actor
{
int BarValue = 118;
public void act()
{
    if(Greenfoot.isKeyDown("f")
    {
        shoot();
    }
}
public void shoot()
    {
            Drone Drone2 = new Drone();
            getWorld().addObject(Drone2, getX() - 13, getY() - 13);
            BarValue--;
    }

public int getBarValue()
{
    return BarValue;
}
}
now in my bar class i want to get the BarValue..
public class DroneBar
{
int DroneBarValue = 118;
private Ship ship = new Ship();

public void act() 
    {
        if(ship.getBarValue() != DroneBarValue)
        {
            DroneBarValue = jumper.getShotEnergy();
            updateImage();
        }
    }
now in updateImage() i want to use the DroneBarValue but my bar class doesn't get it. I works when i return this: return BarValue = 10; But the Value changes and i dont know why it doesnt work...
danpost danpost

2013/2/28

#
The problem is line 4 in the DroneBar class. You are creating a NEW ship. The ship you want to get the value from is in the world (creating a NEW ship object does not get a reference to the one in the world). Remove line 4 in the DroneBar class and start your 'act' method with the following lines:
if (getWorld().getObjects(Ship.class).isEmpty())
{
    getWorld().removeObject(this); // this line is optional
    return;
}
Ship ship = (Ship) getWorld().getObjects(Ship.class).get(0);
You need to login to post a reply.