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

2014/12/31

Switching Image based on actor location

Dillybar Dillybar

2014/12/31

#
Hi, I can't seem to be able to wrap my head around this null pointer exception error. I am attempting to change the image of the flower based on whether mario is to the left or the right of the flower. Here is my code:
public void turnFlower()
    {
        marioX = ((MarioG) getOneIntersectingObject(MarioG.class)).getXCoord();
        if (marioX > getX())
        {
            fLeft = false;
        }
        if (marioX < getX())
        {
            fLeft = true;
        }
    } 
The error occurs on line 3 but I am unsure why there is an error there. Thanks for the assistance :)
danpost danpost

2014/12/31

#
The method 'getOneIntersectingObject' will return a reference to the MarioG object only if it is intersecting the flower. If it is NOT, then 'null' is returned -- and you cannot use 'getXCoord' on a 'null' value. First get the MarioG object, then check for 'null' before trying to execute the 'getXCoord' method on it.
Dillybar Dillybar

2014/12/31

#
ah I see. What can I use in place of getOneIntersectingObject if I want it to always switch, even if mario is not colliding with the flower?
davmac davmac

2014/12/31

#
The best option from a design standpoint is to have the world maintain a reference to the MarioG instance, and have the flower retrieve it from the world, very much like the technique used in tutorial #6. A simpler alternative, not quite as nice from a design standpoint, is to get the list of all MarioG objects in the world (use the 'getObjects' method) and take the first item from the list. Something like:
        marioX = ((MarioG) getObjects(MarioG.class).get(0)).getXCoord();
danpost danpost

2014/12/31

#
Dillybar wrote...
ah I see. What can I use in place of getOneIntersectingObject if I want it to always switch, even if mario is not colliding with the flower?
You can use the world to find out if marioG is in it and then get a reference to it. Like this:
if ( ! getWorld().getObjects(MarioG.class).isEmpty() )
{
    MarioG marioG = (MarioG) getWorld().getObjects(MarioG.class).get(0);
    if ( marioG.getXCoord() != getX() ) fLeft = (marioG.getXCoord() < getX());
}
Dillybar Dillybar

2014/12/31

#
Your code did not return any errors danpost- gonna fiddle around with it now and try to understand it.
danpost danpost

2014/12/31

#
NVM. Fiddle around.
Dillybar Dillybar

2014/12/31

#
ok thanks :)
Dillybar Dillybar

2014/12/31

#
Awesome, I got a working version. Thanks much for the help
You need to login to post a reply.