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

2013/6/10

Is in world?

1
2
Phytrix Phytrix

2013/6/10

#
Basically I'm trying to create a game where the life and score counter in relation to contact with the enemy is controlled in the hero class. Although, when the level changes to a level that does not have the enemy in it, it says:
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.
So is there a way to say only initiate this method when the actor is in the world? Any help would be much appreciated. :)
Zamoht Zamoht

2013/6/10

#
I don't know if there is an easier way, but here is one. Remember to import the List class. import java.util.List;
//change class name from Enemy.class to the name of your enemy class.
List objects = getWorld().getObjects(Enemy.class);
            for (Object object : objects)
            {
                if (object == this)
                {
                    //put code here for what to do if the actor is in the world.
                }
            }
Oh wait... This might not work since getWorld() will fail if the actor is not in a world. Give me a sec I have to eat, but I'll come back later and answer your question.
Phytrix Phytrix

2013/6/10

#
Yeah in trying it that didn't work. I received a null point exception when trying it. Thanks a lot for your help and I'll wait for you to get back :3
Zamoht Zamoht

2013/6/10

#
Okay back again. Don't look at the code I gave you before. So what you can do is use this instead.
if (getWorld() != null)
{
     //The actor is in a world and you can get it's location.
}
But if you are controlling this from the hero class and wants to know if the enemy is in the world you have to change getWorld() to enemy.getWorld() since I assume that your hero has a refference to the enemy.
Phytrix Phytrix

2013/6/10

#
Noob question, but what kind of reference would I need? I don't currently have a reference...
Zamoht Zamoht

2013/6/10

#
Can you show the code for your hero. That will help me a lot to understand what you have and what you are missing.
Phytrix Phytrix

2013/6/10

#
I plan to add the getWorld() != null code in the act method around the initiation of enemyContact().
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.List; 

/**
 * Write a description of class Hero here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Hero extends Actor
{
    GreenfootImage image = getImage();
    WorldSettings worldSettings = (WorldSettings) getWorld();

    public int level;

    int spriteHeight = 75; // cannot use image.getHeight() as the image changes and there is no preset
    int spriteWidth = 75; // cannot use image.getWidth() as the image changes and there is no preset

    private int vSpeed = 2; // vertical speed of the hero
    private int hSpeed = 5; // horizontal speed of the hero
    private int acceleration = 1; // acceleration speed (primarily for gravity)

    private int barHeroValue = 100;

    public boolean jumping;
    public int jumpPower = 20; // jump strength

    public int frame = 1; // default frame of 1 (used for animation)
    public int attackFrame = 1;
    private int animationCounter; // used to slow the frame changes in act method

    private int wolfDead = 50; // so it takes multiple hits to kill the wolf
    private int waitWolf = 0; // so that there is a pause before losing life again

    public int askQuestion = 0;

    /**
     * Constructor for Hero
     */
    public Hero()
    {
        setImage("panda-frame-3.gif");
    }

    /**
     * Act - do whatever the Hero wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        controls();
        isFalling();
        checkNextLevel();
        actAtWorldEdge();

        enemyContact();

        lifeCounter();
        touchingPlatformRight();
        animationCounter++;
    }    

    public void enemyContact()
    {
        Actor wolf = getOneIntersectingObject(Wolf.class);

        if(wolf == null)
            waitWolf = 0;

        if(wolf != null && animateAttack() == true) 
        {
            ScoreCounter scorecounter = worldSettings.getScoreCounter();
            scorecounter.bumpCount(1);

            wolfDead--;

            if(wolfDead <= 0)
            {
                getWorld().removeObject(wolf);
                wolfDead = 50;
            }
        }

        if(wolf != null && animateAttack() != true)
        {
            waitWolf--;

            if(waitWolf == 0)
            {
                WorldSettings worldSettings = (WorldSettings) getWorld();
                Bar bar = worldSettings.bar;
                bar.subtract(10); // 2 shots = 1 life lost. Resets every screen
                barHeroValue = barHeroValue - 50;
                waitWolf = 50;
            }
        }
    }

    public void lifeCounter()
    {
        WorldSettings worldSettings = (WorldSettings) getWorld();
        LifeCounter lifecounter = worldSettings.getLifeCounter();

        if(barHeroValue == 0)
        {
            barHeroValue = 100;

            Bar bar = worldSettings.bar;
            bar.add(100); // 2 shots = 1 life lost. Resets every screen

            lifecounter.bumpCount(-1);
        }

        //if(lifecounter.value == 0)
        // game over
    }

    /**
     * Method for controls
     */
    public void controls()
    {
        if(Greenfoot.isKeyDown("up") && jumping == false)
            jump();

        if(Greenfoot.isKeyDown("left"))
        {
            this.setLocation(getX() -hSpeed, getY());

            if(animationCounter % 4 == 0 && touchingGround() == true || animationCounter % 4 == 0 &&  touchingPlatformTop() == true)
                animateLeft();
        }

        else if(Greenfoot.isKeyDown("right"))
        {
            this.setLocation(getX() +hSpeed, getY());

            if(animationCounter % 4 == 0)
                animateRight();
        }

        if(Greenfoot.isKeyDown("space"))
            animateAttack();
    }

    /**
     * Method for animation while facing right
     */
    public void animateRight()
    {  
        if (frame != 11) 
        {  
            setImage("panda-frame-"+frame+".gif"); 
            frame++;   
        }    
        else 
        {  
            frame = 1; //this makes the animation start again from the beginning (frame 1)  
        }  
    }

    /**
     * Method for animation while facing left
     */
    public void animateLeft()
    {
        if (frame != 11 &&  touchingGround() == true || frame != 11 &&  touchingPlatformTop() == true) 
        {  
            setImage("panda-frame-"+frame+".gif");    
            getImage().mirrorHorizontally();
            frame++;    
        }    
        else 
        {  
            frame = 1; //this makes the animation start again from the beginning (frame 1)  
        }  
    }

    public boolean animateAttack()
    {            
        if(animationCounter % 4 == 0)
        {
            if (attackFrame != 9) 
            {  
                setImage("panda-attack-"+attackFrame+".gif");    
                attackFrame++;    
            }    
            else 
            {  
                attackFrame = 1; //this makes the animation start again from the beginning (frame 1)  
            }  
        }

        if(Greenfoot.isKeyDown("space"))
            return true;
        else
            return false;
    }

    /**
     * Method for when objects of this class are not in contact with ground
     */
    public void falling()
    {
        setLocation(getX(), getY() + vSpeed);
        if(vSpeed <= 18)
        {
            vSpeed = (vSpeed + acceleration) ;
        }
        jumping = true;
    }

    /**
     * Are objects of this class touching the ground?
     */
    public boolean touchingGround()
    {         
        Actor ground = getOneObjectAtOffset(0, spriteHeight/2, Ground.class);
        if(ground != null)
        {
            moveToGround(ground);
            return true;
        }
        else
        {
            jumping = true;
            return false;
        }
    }

    /**
     * Method for moving objects of this class to the ground
     */
    public void moveToGround(Actor ground)
    {
        int groundHeight = ground.getImage().getHeight();
        int newYG = ground.getY() - (groundHeight + getImage().getHeight())/2;

        setLocation(getX(), newYG);
        jumping = false;
    }

    /**
     * Are objects of this class touching the platforms?
     */
    public boolean touchingPlatformTop()
    {         
        Actor platform = getOneObjectAtOffset(0, spriteHeight/2, Platform.class);

        if(platform != null)
        {
            moveToPlatform(platform);
            return true;
        }
        else
        {
            jumping = true;
            return false;
        }
    }

    /**
     * Method for moving objects of this class to the ground
     */
    public void moveToPlatform(Actor platform)
    {
        int platformHeight = platform.getImage().getHeight();
        int newYP = platform.getY() - (platformHeight + getImage().getHeight())/2;

        setLocation(getX(), newYP);
        jumping = false;
    }

    public boolean touchingPlatformRight()
    {
        int spriteWidth = getImage().getWidth();
        int xDistance = (int)(spriteWidth/2);

        Actor platformRight = getOneObjectAtOffset(xDistance, 0, Platform.class);

        if(platformRight != null)
        {
            stopPlatformRight(platformRight);
            return true;
        }
        else
        {
            return false;
        }
    }

    public void stopPlatformRight(Actor platformRight)
    {      
        int wallWidth = platformRight.getImage().getWidth();
        int newX = platformRight.getX() - (wallWidth + getImage().getWidth())/2;

        setLocation(newX -5, getY());
    }

    public boolean touchingPlatformLeft()
    {
        int spriteWidth = getImage().getWidth();
        int NegXDistance = spriteWidth/-2;

        Actor platformLeft = getOneObjectAtOffset(NegXDistance, 0, Platform.class);

        if(platformLeft != null)
        {
            stopPlatformLeft(platformLeft);
            return true;
        }
        else
        {
            return false;
        }
    }

    public void stopPlatformLeft(Actor platformLeft)
    {      
        int wallWidth = platformLeft.getImage().getWidth();
        int newX = platformLeft.getX() - (wallWidth + getImage().getWidth())/2;

        setLocation(newX +5, getY());
    }

    /**
     * Are objects of this class falling?
     */
    public void isFalling()
    {
        if(touchingGround() || touchingPlatformTop())
        {
            vSpeed = 0;
        }
        else
        {
            falling();
        }
    }

    /**
     * Booleans to test whether or not objects of this class are in contact with the edge(s) of the world
     */
    public boolean atMinX()  
    {  
        if(getX() < spriteWidth/2)  
            return true;  
        else  
            return false;  
    }

    public boolean atMaxX()
    {
        if(getX() > getWorld().getWidth() - spriteHeight/2)
            return true;  
        else  
            return false;  
    }

    public boolean atMinY()
    {
        if(getY() < spriteHeight/2) 
            return true;
        else  
            return false;  
    }

    /** end of booleans for at(Min/Max)(X/Y) */

    /**
     * Method to see if objects of this class are at the world's edges (tests the above booleans)
     */
    public void actAtWorldEdge()
    {
        //         if(atMinX() == true)
        //         {
        //             setLocation(getX() + hSpeed, getY());
        //         }
        // 
        //         if(atMaxX() == true)
        //         {
        //             setLocation(getX() - hSpeed, getY());
        //         }
        // 
        //         if(atMinY() == true)
        //         {
        //             setLocation(getX(), getY() + hSpeed);
        //         }
    }

    /**
     * Method which explains what is done when objects of this class are jumping
     */
    public void jump()
    {
        vSpeed = vSpeed - jumpPower;
        jumping = true;
        falling();
    }

    /**
     * Check whether we should go to the next level, and if yes, start the next level
     */
    private void checkNextLevel()
    {

        // if (getOneIntersectingObject(LevelComplete.class) != null)
        if (atMaxX() == true)
        {
            WorldSettings worldSettings = (WorldSettings) getWorld();

            if (worldSettings.level == 1) 
            {
                worldSettings.level = 2;
                Greenfoot.setWorld(new LevelB(this));
                getWorld().removeObject(this);
            }
            else if (worldSettings.level == 2) 
            {
                worldSettings.level = 3;
                Greenfoot.setWorld(new LevelC(this));
                getWorld().removeObject(this);
            }
            else if (worldSettings.level == 3) 
            {
                worldSettings.level = 4;
                Greenfoot.setWorld(new LevelD());
                getWorld().removeObject(this);
            }
            else if (worldSettings.level == 4) 
            {
                worldSettings.level = 5;
                Greenfoot.setWorld(new LevelE());
                getWorld().removeObject(this);
            }
            else if (worldSettings.level == 5) 
            {
                worldSettings.level = 6;
                Greenfoot.setWorld(new LevelF());
                getWorld().removeObject(this);
            }
        }
    }
}
Zamoht Zamoht

2013/6/10

#
I have to be honest and say that I'm not sure anymore. But first of all I think that
worldSettings.level = 2;
Greenfoot.setWorld(new LevelB(this));  getWorld().removeObject(this); 
Is a problem since I bet that Greenfoot.setWorld(new LevelB(this)); Creates a new world and adds the hero to it. Since you change the world the old world is deleted and therefore you delete the hero from the new world when using getWorld().removeObject(this); because getWorld() gives you a reference to the new world. Hope this makes sense. Try remove getWorld().removeObject(this); and tell me what happens. If this doesn't work please send the code for LevelB as well.
Phytrix Phytrix

2013/6/10

#
It works fine without the enemy interaction with that code. I think it's an issue because when I create LevelB(Hero hero) the hero is added before anything else, so even if I set the super to false and have the wolf running around off the screen, it stops the scenario first...
Zamoht Zamoht

2013/6/10

#
It really shouldn't crash because there is no wolf in the world. Okay I'm sorry that I haven't solved it yet.. Could you tell me what line exactly the error refers to? Else could you upload the scenario so I could download it and see for myself?
Phytrix Phytrix

2013/6/10

#
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. at greenfoot.Actor.failIfNotInWorld(Actor.java:663) at greenfoot.Actor.getOneIntersectingObject(Actor.java:912) at Hero.enemyContact(Hero.java:66) at Hero.act(Hero.java:56) at greenfoot.core.Simulation.actActor(Simulation.java:565) at greenfoot.core.Simulation.runOneLoop(Simulation.java:523) at greenfoot.core.Simulation.runContent(Simulation.java:213) at greenfoot.core.Simulation.run(Simulation.java:203) Which is in reference to Actor wolf = getOneIntersectingObject(Wolf.class);
Zamoht Zamoht

2013/6/10

#
Okay try this.
public void act()   
    {  
        controls();  
        isFalling();  
        checkNextLevel();  
        actAtWorldEdge();  
  
        if (getWorld() != null)
             enemyContact();  
  
        lifeCounter();  
        touchingPlatformRight();  
        animationCounter++;  
    } 
Phytrix Phytrix

2013/6/10

#
That seems to fix my issue, although I'm now receiving an error java.lang.NullPointerException at Hero.lifeCounter(Hero.java:107) at Hero.act(Hero.java:59) which is in reference to: LifeCounter lifecounter = worldSettings.getLifeCounter(); I had a quick look over and couldn't exactly see why. I'm new-ish (maybe 2 months or so) to Greenfoot so sorry for all the questions, but here's my WorldSettings code. I'd appreciate it if you could have a look over it for me :)
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Scrollbar;
import java.util.List;
import greenfoot.Actor;
import greenfoot.GreenfootImage;
import java.util.Calendar;
import java.awt.Color;
//import Scrollbar.AccessibleAWTScrollBar.*;

/**
 * Write a description of class WorldSettings here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */

public class WorldSettings extends World
{    
    private ScoreCounter theScoreCounter;
    private LifeCounter theLifeCounter;
    public Hero hero;
    public Bar bar = new Bar("Player 1", "Health Points", 25, 100);

    public static int level;
    private static int testLevel = 0;

    /**
     * Constructor for class WorldSettings
     */
    public WorldSettings()
    {    
        super(800, 550, 1, false); // 3 x image width

        hero = new Hero();
        addObject(hero, 300, 140);

        theScoreCounter = new ScoreCounter();
        addObject(theScoreCounter, 700, 40);

        theLifeCounter = new LifeCounter();
        addObject(theLifeCounter, 100, 40);

        addObject(bar, 375, 40);

        if(testLevel == 0)
        {
            Greenfoot.setWorld(new MainMenu());
            testLevel = 1;
        }

        removeObject(hero);

        Ground ground = new Ground();
        addObject(ground, 400, 500);
    }

    public ScoreCounter getScoreCounter()
    {
        return theScoreCounter;
    }

    public LifeCounter getLifeCounter()
    {
        return theLifeCounter;
    }

    public void act()
    {
        setPaintOrder(QI.class, IncorrectAI.class, CorrectAI.class, Hero.class, Wolf.class, SmallPBonus.class, PBonus.class, Platform.class, Rock.class, Ground.class); //insert other bonuses after hero

        //if (hero.enemyContact() == true)
        //bar.subtract(1);
    }
}
Zamoht Zamoht

2013/6/10

#
Minor detail put "setPaintOrder(QI.class, IncorrectAI.class, CorrectAI.class, Hero.class, Wolf.class, SmallPBonus.class, PBonus.class, Platform.class, Rock.class, Ground.class);" in the constructor since it only has to be called once. Okay this crashes because you call getWorld() when the hero is not in a world. To fix this just put getWorld() != null around your whole act method for the hero.
Zamoht Zamoht

2013/6/10

#
public void act()   
    {  
        if (getWorld() != null)
       {
           controls();  
           isFalling();  
           checkNextLevel();  
           actAtWorldEdge();  
  
          enemyContact();  
  
           lifeCounter();  
           touchingPlatformRight();  
           animationCounter++;  
        }
    } 
There are more replies on the next page.
1
2