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

2016/1/15

Can't find out how to delete moving object at edge of world

Arakniode Arakniode

2016/1/15

#
So, I would like to delete an object of the "Crab" class when it reaches the end of the world, but it doesn't quite work... have any ideas? Here's my code:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Crabs are Lobster food
 */
public class Crab extends Actor
{
    /**
     * Act - do whatever the Crab wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        isInWorld();
        crabMovement();
    }
    public void crabMovement ()
    {
        int crabRandomMoveChoice = Greenfoot.getRandomNumber(4); //makes crab move in random directions
        if(crabRandomMoveChoice == 0 && isInWorld()){
            setLocation(getX()+4, getY());
        }
        if(crabRandomMoveChoice == 1 && isInWorld()){
            setLocation(getX()-4, getY());
        }
        if(crabRandomMoveChoice == 2 && isInWorld()){
            setLocation(getX(), getY()+4);
        }
        if(crabRandomMoveChoice == 3 && isInWorld()){
            setLocation(getX()+4, getY()-4);
        }
    }
    public boolean isInWorld()
    {
        if(getX() <= 5 || getX() >= getWorld().getWidth() -5) //removes crab if he touches the edge
        {
            getWorld().removeObjects(getWorld().getObjects(Crab.class));
            return false;
        }
        if (getY() <= 5 || getY() >= getWorld().getHeight() -5)
        {
            getWorld().removeObjects(getWorld().getObjects(Crab.class));
            return false;
        }
        else //if he doesn't touch the edge, continue moving
        {
            crabMovement();
            return false;
        }
    }
}
Thanks in advance!
Super_Hippo Super_Hippo

2016/1/15

#
Arakniode wrote...
but it doesn't quite work...
This isn't very accurately. You created an infinite loop there. Line 14 calls the 'isInWorld' method, this one calls the 'crabMovement' method (line 47) which itself calls the 'isInWorld' method again. In line 15, you even want to start all this again. The crab never moves because 'isInWorld' always returns 'false'. Even if this would not happen and your crab would move, you will probably get a nullpointer exception when it moves to the edge of the world. This is because if it is at the edge, you remove it from the world (call to the method from line 14) and then you call it again (line 20 or similar). The 'getWorld()' will return 'null' and you get the error because you are trying to use methods on it. To avoid that, you could simply remove lines 14 and 47 and change line 48 to 'return true;'. There are other possibilities to improve your code though.
You need to login to post a reply.