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

2017/12/1

Pausing the world

I have been looking around for a way to pause the entire world without having to press the run button to start again. I get a NullPointerException(line 18) when I try to use a boolean from my world. This is my world code:
public class MyWorld extends World
{
    public boolean isRunning;

    public MyWorld()
    {    
        super(1000, 600, 1);
        
        GreenfootImage background = new GreenfootImage(getBackground());
        background.setColor(new Color(200, 200, 200));
        background.fill();
        setBackground(background);
        addObject(new Test(), 50, getHeight()/2);
        isRunning = true;
    }
    
    public void act()
    {
        checkPause();
    }
    
    private void checkPause()
    {
        String keyPressed = Greenfoot.getKey();
        if ("p".equals(keyPressed))
        {
            if (isRunning)
            {
                isRunning = false;
            } else if (!isRunning) {
                isRunning = true;
            }
        }
    }
    
    public boolean isRunning()
    {
        return isRunning;
    }
}
This is my Actor code:
public class Test extends Actor
{
    MyWorld world = (MyWorld)getWorld();
    public void act() 
    {
        if (world.isRunning)
        {
            setLocation(getX() +5, getY());
        }

        // while (world.isRunning())
        // {
            // Greenfoot.delay(1);
            // setLocation(getX() +5, getY());
        // }
    }    
}
I created isRunning() in an attempt to make it work, but it did exactly the same. If anyone knows, help would be appreciated.
I have resolved the issue. I'll post the code just in case anyone needs this later. My world:
public class MyWorld extends World
{
    public boolean isRunning;
 
    public MyWorld()
    {    
        super(1000, 600, 1);
        
        //This just creates my background
        GreenfootImage background = new GreenfootImage(getBackground());
        background.setColor(new Color(200, 200, 200));
        background.fill();
        setBackground(background);
        
        //This is my actor
        addObject(new Test(), 50, getHeight()/2); 
        
        isRunning = true;
    }
     
    public void act()
    {
        String keyPressed = Greenfoot.getKey();
        if ("p".equals(keyPressed))
        {
            isRunning = !isRunning;
        }
    }
}
This is my actor:
public class Test extends Actor
{
    public void act() 
    {
        if (((MyWorld)getWorld()).isRunning)
        {
            //post ALL act code here
        }
    }    
}
You need to login to post a reply.