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

2016/8/7

Make an invisible actor visible with getObjectsInRange

ecorlette ecorlette

2016/8/7

#
I currently have an actor which is invisible, and I want it to become visible if another actor comes within my set range of it. Though I cannot seem to figure out how to do so. Currently I have
public void ifCrabInRange()
   {
       List<Crab> enemies = getObjectsInRange(50, Crab.class);
   }
And I do have
import java.util.List;
imported already at the beginning of the class.
erdelf erdelf

2016/8/7

#
Basically just check if the list you created is empty and then set the image accordingly. oh and you need to call that method in the act method so that it checks constantly. the boolean is just for perfomance and so the garbace collector doesn't have about sixty images to clean every two seconds.
public void act() {
    ifCrabInRange();
}
boolean visible;
public void ifCrabInRange()
{
    if(getObjectsInRange(50, Crab.class).isEmpty())
    {
       if(visible)
       {
              setImage(new GreenfootImage(1,1));
              visible = false;
       }
     } else
       if(!visible)
       {
              setImage("whatever image you want");
              visible = true;
       }
}
danpost danpost

2016/8/7

#
Better would probably be to just use the transparency factor of the image. Then, there will not be any images going to the garbage collector and there will not be any need for the boolean, either (you could check for the current transparency value of the image, but even that is not necessary). The following line should be sufficient:
setTransparency(getObjectsInRange(50, Crab.class).isEmpty() ? 0 : 255);
You need to login to post a reply.