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

2018/3/1

Projectiles give errors when at the edge of the world

Soulcrusher13 Soulcrusher13

2018/3/1

#
I'm a noob here. I get the following message when the projectile reaches the end of the world. I've tried many things to correct this but none work. I don't get the error when I shoot up or down but I do get it when I shoot left or right. What am I doing wrong? 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.
public class Shot extends Actor
{
    private int direction, speed;
    public Shot(int dir)
    {
        direction = dir;
        speed = 15;
    }
    public void act() 
    {
        setRotation(direction);
        move(speed);
        setLocation(getX() - 1, getY());
    if (getOneIntersectingObject(Seal.class) != null)
    {
        getWorld().removeObject(this);
        return;
    }
    if (isAtEdge())  
    {
        getWorld().removeObject(this);
        return;
    }
        }
    }
danpost danpost

2018/3/1

#
Try adding 'else' at the beginning of line 19.
Soulcrusher13 Soulcrusher13

2018/3/1

#
I tried using else if (isAtEdge()) but the error persists.
danpost danpost

2018/3/1

#
Soulcrusher13 wrote...
I tried using else if (isAtEdge()) but the error persists.
My goodness. I totally overlooked the 'return;' statements in the code. Adding 'else' did not do a thing (at all). Please clear your terminal, recreate the error and copy/paste the output here for review.
Soulcrusher13 Soulcrusher13

2018/3/1

#
Solved it! I had to erase line 13 I guess. This is how it came out. thanks for the help tho. I will be looking for ways to optimize it.
public class Shot extends Actor
{
    private int direction, speed;
    public Shot(int dir)
    {
        direction = dir;
        speed = 15;
    }
    public void act() 
    {
        setRotation(direction);
        move(speed);
    if (getOneIntersectingObject(Seal.class) != null)
    {
        getWorld().removeObject(this);
    }
    if (isAtEdge())  
    {
        getWorld().removeObject(this);
    }
        }
    }
danpost danpost

2018/3/1

#
You will need either the 'else' or the 'return;' statements (at least the first one). I do not see how line 13 would have caused the error you were getting. The act method will not execute for an actor not in a world and there is nothing that will remove it before that line.
You need to login to post a reply.