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

2014/10/10

Projectiles removing themselves

ajmetal ajmetal

2014/10/10

#
My game is called FirstProject and is published on this website link here: http://www.greenfoot.org/scenarios/12250 What I'm trying to do is code my laser object to remove itself whenever it contacts one of the aliens (SpaceFly.class) and when it reaches the edge of the world. I've tried as many iterations of my current code and other methods I could think of and I can't get it to work properly. I always get a runtime error saying: "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." This is my most straightforward attempt: import greenfoot.*; public class Laser extends Actor { private int speed; public Laser() { speed = 15; setRotation(270); } public void act() { move(speed); checkHit(); if(getY() < 20 || getY() > getWorld().getWidth() - 20) { getWorld().removeObject(this); } } private void checkHit() { if (isTouching(SpaceFly.class)) { removeTouching(SpaceFly.class); getWorld().removeObject(this); } } }
Super_Hippo Super_Hippo

2014/10/10

#
The problem is, that you when you remove the object in the 'checkHit' method, then it is no in the world anymore and can't check the conditions for the if-block because it doesn't have a position in the world anymore. There are some ways to day this. Either you can use a 'if (getWorld()!=null)' right before using theother if-block, or you have something like this:
   public void act()
    { 
        move(speed);
        if(checkHit() || getY() < 20 || getY() > getWorld().getWidth() - 20)
        {
            getWorld().removeObject(this);
        }
    }
    private boolean checkHit()
    {
       if (isTouching(SpaceFly.class))
       {
           removeTouching(SpaceFly.class);
           return true;
       }
       return false;
    }
ajmetal ajmetal

2014/10/10

#
So, in the first if block in the act() method, it invokes the checkHit() method and interprets the true or false value to decide whether or not to execute the next line? Just wanna make sure I'm understanding why this works. I just implemented it and it works, thanks!
Super_Hippo Super_Hippo

2014/10/10

#
The 'checkHit' method now returns a boolean. So if the Laser objects touches a SpaceFly, it will return true. Then, or if it is at an edge of the world (only top or bottom as it is right now), it will be removed from the world.
You need to login to post a reply.