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

2013/7/29

How do I get an object to disappear off-screen?

Blake1996 Blake1996

2013/7/29

#
I am making a game in which the player has to evade incoming objects, however the objects get stuck on the edge of the word. Thanks for taking the time to read my question.
danpost danpost

2013/7/29

#
The World class API has a method to remove an object from the world. Click to 'Documentation link above and check the API documentation out 'online'.
Zamoht Zamoht

2013/7/29

#
Okay first of all you have to put a false argument at the end of your world constructor. public NameOfYourWorld() { super(width, height, cellSize, false); //rest of your code. } Now your objects will be able to move out of the world bounds. Now in the class you want to disappear add this method:
public boolean isOffScreen()
{
     if (getX() < 0 - getImage().getWidth()/2 || 
getX() > getWorld.getWidth() + getImage().getWidth()/2 ||
getY() < 0 - getImage().getHeight()/2 ||
getY() > getWorld().getHeight() + getImage().getHeight()/2)
     {
          return true;
     }
     return false;
}
Then in the act method add this:
public void act()
{
     if (isOffScreen())
     {
          getWorld().removeObject(this);
     }
     //rest of your act code.
}
The code is not tested but should work.
Blake1996 Blake1996

2013/7/30

#
Thank you both for your replies, however Zamoht I couldn't figure what exactly I had to do, and danpost could you please be a little more specific?
Zamoht Zamoht

2013/7/30

#
Okay which part didn't you get?
danpost danpost

2013/7/30

#
@Blake1996, Zamoht used the method at line 5 of the 'act' method given. His 'isOffScreen' method is similar to the 'atWorldEdge' method supplied in the 'Animal' class (if you are familiar with that). If the incoming objects that need to be avoided travel only one way across the screen then only the particular edge you want to remove the objects at need to be checked. So, basically, if they are added at the right edge and move across to the left, you could use:
if (getX() == 0) getWorld().removeObject(this);
You would put this line in the 'act' method of the class that creates the objects you need to evade.
You need to login to post a reply.