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

2018/3/5

Problem with atWorldEdge()

Kolyma Kolyma

2018/3/5

#
Hi again, in my project, the Lemon should disappear as soon as it reaches the end of the world. However, my code does not work that way. What did I do wrong?
public class Lemon extends Actor
{

    /**
     * 
     */
    public Lemon()
    {
        turn(90);
    }

    /**
     * Act - do whatever the Lemon wants to do. This method is called whenever the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act()
    {
        move(4);
        Actor mädchen = getOneIntersectingObject(Mädchen.class);
        if (mädchen!=null)
        {
            Counter counter = new Counter();
            ((MyWorld)getWorld()).getCounter().addScore();
        }
    }
    public boolean atWorldEdge()
    {
        if (atWorldEdge())
        {
            getWorld().removeObjects(getWorld().getObjects(Lemon.class));
        }    
        {
            return Lemon.class;
        }
    }
}
danpost danpost

2018/3/5

#
The problem is that you named your method using the name of an already declared method for the Lemon object. By doing so, any call to it go to this method (meaning line 27 has the method being called from within itself -- which then calls itself; which then ... (you get the picture -- an "infinite" pit of calls to itself, probably causing a StackOverflowError). To have line 27 call the Actor class method with that name, you can use:
if (super.atWorldEdge())
danpost danpost

2018/3/5

#
Also, you are trying to return a Class object from method, yet it is declared to return a boolean value. Plus, the method is not even being called from outside itself. So, you were not getting the error; the code just was not being executed. Another issue is that you are creating a new Counter object to add a score to which does nothing for any Counter object that may be in the world.
danpost danpost

2018/3/5

#
Sorry, got something else wrong. There is no 'atWorldEdge' method in the Actor class; still, however, the method, if ever called, would call itself and eventually cause the error mentioned. To deal with your stated issue, remove lines 24 to 26 and 31 to 33; then, change line 29 to this:
if (isAtEdge()) getWorld().removeObject(this);
Kolyma Kolyma

2018/3/5

#
To deal with your stated issue, remove lines 24 to 26 and 31 to 33. I also removed the lines 27 and 28 and changed line 29 like you said. Now its working. Thank you very much!
danpost danpost

2018/3/5

#
Kolyma wrote...
I also removed the lines 27 and 28 and changed line 29 like you said.
Very good. That is what I intended.
You need to login to post a reply.