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

2018/8/5

How can I make an object disappear as soon as it hits the edge of the map?

MinexTheOne MinexTheOne

2018/8/5

#
I was trying to use this code, it doesn't show anything wrong with it when I wrote it down, but when it comes in contact of the edge of the map an error message pops up saying; at hook.Vanish(hook.java:35) at hook.act(hook.java:23). (Hook is the subclass I wanna make it disappear. And vanish is what the method is called which tries to make it vanish.) public void Vanish() { World world; world = getWorld(); if (getX() >= getWorld().getWidth()-1) world.removeObject(this); if(getY() >= getWorld().getHeight()-1) world.removeObject(this); }
danpost danpost

2018/8/5

#
MinexTheOne wrote...
I was trying to use this code, it doesn't show anything wrong with it when I wrote it down, but when it comes in contact of the edge of the map an error message pops up saying; at hook.Vanish(hook.java:35) at hook.act(hook.java:23). (Hook is the subclass I wanna make it disappear. And vanish is what the method is called which tries to make it vanish.) << Code Omitted >>
Although you did not include what type of error you were getting, it is not to difficult to tell it was probably an IllegalStateException (due to actor not in world). If your actor touches the right edge of the world and is then removed, the actor will not have a valid y-coordinate location to get when checking for the actor touching the bottom edge. You could just check to make sure the actor is still in the world between the two checks; but, an easier solution is to combine the two checks:
1
2
3
4
5
6
public void Vanish()
{
    World world = getWorld();
    if (getX() >= world.getWidth()-1 || getY() >= world.getHeight()-1)
        world.removeObject(this);
}
You need to login to post a reply.