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

2022/2/10

How to use an actor dependency only when the needed actor is there

Courier_ Courier_

2022/2/10

#
I'm playing with the crab/lobster game scenario, and I've given the lobster the ability to seek and destroy the crab. I can't figure out how to make this dependant function only work when a crab(TestCrab) is on the world. Anyone have an idea? current TestLobster code is the following
    public void act()
    {
        {
            
            Actor LC = (Actor)getWorld().getObjects(TestCrab.class).get(0);
            
            {
            turnTowards(LC.getX(), LC.getY());
            move(3);
        }
            if(isTouching(TestCrab.class))
            {
                removeTouching(TestCrab.class);
            }
            }
    }
danpost danpost

2022/2/10

#
Courier_ wrote...
I'm playing with the crab/lobster game scenario, and I've given the lobster the ability to seek and destroy the crab. I can't figure out how to make this dependant function only work when a crab(TestCrab) is on the world. << Code Omitted >>
Try this:
public void act()
{
    java.util.List crabList = getWorld().getObjects(TestCrab.class);
    if ( ! crabList.isEmpty() )
    {
        Actor crab = (Actor) crabList.get(0);
        if (! intersects(crab))
        {
            turnTowards(crab.getX(), crab.getY());
            move(3);
        }
        else getWorld().removeObject(crab);
    }
}
Line 4 could also be done this way:
if (crabList.size() > 0)
Courier_ Courier_

2022/2/11

#
Thanks! that worked how I needed it to
danpost danpost

2022/2/11

#
Courier_ wrote...
Thanks! that worked how I needed it to
That is because an element is not trying to be extracted from a list without any elements. A test is done to the list to ensure an element exists in the list before extracting the element.
You need to login to post a reply.