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

2013/3/8

An actor delete itself?

So I have an DamageActor that will move for a specific amount of time, and then remove itself from the world. However, I can't see to figure that out. I followed the information on this discussion: http://www.greenfoot.org/topics/1462 but it didn't seem to work. Here's my code:
public void act()
    {
        if(getWorld() == null)
           return;
        if(isFlipped)
            moveLeft();
        else
            moveRight();
        update();
    }

    public void update()
    {
        myDistance--;
        if(myDistance <= 0)
        {
            removeSelf();
            return;
        }
    }

    public void removeSelf()
    {
        myWorld.removeObject(this);
    }
I keep getting a NullPointerException. Other note: I'm testing my code using a DamageActor subclass.
Answer found! I shouldn't have made a private variable named myWorld. I used getWorld() instead, and that worked.
danpost danpost

2013/3/8

#
Let me start by cleaning up the code you provided above. First, lines 3 and 4 are not necessary, as the act method is not called if the actor is not in the active world. Next, line 18 is not necessary, as the method has no more statements and will be exited at that point anyway. (I had this: "Finally, line 24 should use 'getWorld()' instead of 'myWorld'." before I saw your secondary posting). 'update' is a weak name for the method, as it does not really say what the method updates. Possibly better might be 'checkDistance' or 'checkDeath' (even 'updateAge' would be better than just 'update').
Alright, thanks for the tips. I am still getting used to proper method names. I was thinking it would be an overall update, with different values being added/subtracted. Maybe I could have an "updateEverything()" method with individual update methods inside the update.
You need to login to post a reply.