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

2023/12/8

Good afternoon, I have some problem with my code. Stone should disappear when the relocation is equals to 3. But it's triggering an eror. Can you please help me?

Ondřej Ondřej

2023/12/8

#
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Stone here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Stone extends Enemy
{
    private int relocation;
    public Stone()
    {
        turn(90);
    }
    
    public void act()
    {
        move(3);
        
        removing();
        colision();
    }
    
    public void colision()
    {
        if(isTouching(Blast.class))
        {
            removeTouching(Blast.class);
            getWorld().removeObject(this);
        }
    }
    
    public void removing()
    {
        if (isAtEdge() & relocation <= 1)
        {
            setLocation(50 + Greenfoot.getRandomNumber(550), 1);
            relocation ++;
        }
        
        if(relocation == 3)
        {
            getWorld().removeObject(this);
        }
    }
}
Ondřej Ondřej

2023/12/8

#
PS. in line 36 is 2 not 1 (relocation <= 2).
nccb nccb

2023/12/8

#
In Greenfoot, you cannot call getWorld() after you have removed yourself from the world. So the problem is that line 44 removes you, but then you call colision() which will give an error on line 30 (or possibly 27 already). One simple option is to reorder the calls to removing() and to colision().
Ondřej Ondřej

2023/12/8

#
Thanks you for help. Now I understand this.
danpost danpost

2023/12/9

#
nccb wrote...
One simple option is to reorder the calls to removing() and to colision().
I don't think that will quite do it. Both method have the potential to remove this actor and both immediately require the actor to be in a world (for isTouching in colision fails or isAtEdge in removing fails). Simply check if this actor is in the world after calling either colision or removing:
colision();
if (getWorld() == null) return;
removing();
if (getWorld() == null) return;
You can skip the last line if at the end of the method (if a return is performed anyway).
nccb nccb

2023/12/9

#
You're right, danpost, I hadn't spotted that colision can also remove the object.
You need to login to post a reply.