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

2021/4/9

Check if objects of an actor are available

meltHam meltHam

2021/4/9

#
Hi all, I am trying to program a game which the player controls a character that shoots homing projectiles towards enemies. I have managed to implement these homing missiles but once there are no enemies left to shoot at, the program gives a NullPointerException error because it cannot find any enemies to shoot at. My idea is that some way to check if there are any of these objects are left would help get around this problem and just allow the player to shoot projectiles without any homing or no projectiles at all. Any help would be appreciated :)
Super_Hippo Super_Hippo

2021/4/9

#
Show your code. You probably only need to add an if-condition to check if your object reference is “null”.
meltHam meltHam

2021/4/9

#
This is the code for the projectile that is shot by the character. The enemy is the "WalrusWithSnowball". The error given by the program is actually an IndexOutOfBoundsException.
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

public class PinguSnowball extends Actor
{
    
    int snowballRemoved = 0;
    
    public PinguSnowball()
    {
        setImage("snowball.png");
        GreenfootImage image = getImage();
        image.scale(image.getWidth() / 8, image.getHeight() / 8);
        setImage(image);
    }
    
    public void act() 
    {
        move(10);
        WalrusWithSnowball location = (WalrusWithSnowball)getWorld().getObjects(WalrusWithSnowball.class).get(0);
        turnTowards(location.getX(), location.getY());
            
        snowballRemoved = 0;
            
        Actor wallCell = getOneIntersectingObject(Wall.class);
        if (wallCell !=null)
        {
            getWorld().removeObject(this);
            snowballRemoved = 1;
        }
            
        if (snowballRemoved == 0)
        {
            Actor touchingWalrusWithSnowball = getOneIntersectingObject(WalrusWithSnowball.class);
            if (touchingWalrusWithSnowball !=null)
            {
                getWorld().removeObject(this);
                touchingWalrusWithSnowball.getWorld().removeObject(touchingWalrusWithSnowball);
            }
        }
    }    
}
Super_Hippo Super_Hippo

2021/4/9

#
You can check if there are any WalrusWithSnowball objects in the world with this:
if (!getWorld().getObjects(WalrusWithSnowball.class).isEmpty())
So you can check if there are any elements in the list before you try to get the first element.
meltHam meltHam

2021/4/9

#
if (!getWorld().getObjects(WalrusWithSnowball.class).isEmpty())
        {
            WalrusWithSnowball location = (WalrusWithSnowball)getWorld().getObjects(WalrusWithSnowball.class).get(0);
            turnTowards(location.getX(), location.getY());
        }
Here's how I put that into my code and it works, thank you!
You need to login to post a reply.