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

2014/2/5

Help with getObjectsInRange

magnadian magnadian

2014/2/5

#
Hello I am new to this and have been messing around with the crab scenerio. What I'm trying to do is have the image of the crab change when I'm approaching the worm. From the description on the API this is what I would want to use but I can't get it to work. Please help. Thanks
danpost danpost

2014/2/5

#
You should have noted that the 'getObjectsInRange' method returns a List object. The List class API on the Java site might shed some light as to what methods could be useful at this point.
magnadian magnadian

2014/2/5

#
Could I get an example to program this action?
magnadian magnadian

2014/2/5

#
I was able to acheive what I wanted by doing this. public void openMouth() { if (!getObjectsInRange(75, Worm.class).isEmpty()) { Worm worm = (Worm) getObjectsInRange(75, Worm.class).get(0); setImage("Openmouth.png"); } else { setImage("Closemouth.png"); } }
danpost danpost

2014/2/6

#
There is no need to acquire a reference to the worm; only that you know one is there. You can remove the line beginning 'Worm worm =...'. For future reference, keep in mind that it is not advisable to have the image of an actor set every act method if you do not need to. You could add a boolean field to track which image is currently showing (or whether a worm was detected previously or not) and if the value of the boolean does not match up with the result of the detection, change the image:
// instance field
private boolean wormPreviouslyInRange = false;
// in code
boolean wormInRange = !getObjectsInRange(75, Worm.class).isEmpty();
if (!wormPreviouslyInRange && wormInRange) setImage("Openmouth.png");
if (wormPreviouslyInRange && !wormInRange) setImage("Closemouth.png");
wormPreviouslyInRange = wormInRange;
danpost danpost

2014/2/6

#
This is essentially the same without declaring the local boolean field and is a mite bit easier to follow. The first 'if' condition checks to see if the state of worms in range has changed. Therefore, the image is only changed when the state changes.
// instance field
private boolean wormInRange = false;
// in code
if (wormInRange == getObjectsInRange(75, Worm.class).isEmpty())
{
    wormInRange = !wormInRange;
    if (wormInRange) setImage("Openmouth.png");
    if (!wormInRange) setImage("Closemouth..png");
}
Line 8 could be changed from 'if (!wormInRange)' to simply 'else'.
You need to login to post a reply.