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

2017/4/2

Help with removing Actors of the same class

1
2
Super_Hippo Super_Hippo

2017/4/3

#
or find a way that all the Ants, whether an Ant or SeekerAnt, to turn towards the other Ants and chase them
How is that supposed to work? Every ant is chasing each other? By the way, an Ant is an Ant, no matter if it is alive, dead or "converted". So you should not create different classes for different states of one class.
Asiantree Asiantree

2017/4/3

#
Yes, every Ant is meant to chase each other. So, how can I get every Ant to seek each other out in the Ant act method instead of creating a new actor?
Super_Hippo Super_Hippo

2017/4/3

#
But... then all ants will be at one position sooner or later and dying one after the other.
Asiantree Asiantree

2017/4/3

#
Yes, they will all die, that is the point. I need all Ants to seek each other out and turn into a DeadAnt.
Super_Hippo Super_Hippo

2017/4/3

#
So wait, are all Ants hunting SeekerAnts and all SeekerAnts hunt Ants or do normal Ants also hunt normal Ants? Because then, when it is implemented like "find the nearest ant and run for it", then two will find each other and will stay on one position.
Asiantree Asiantree

2017/4/3

#
I removed the SeekerAnt class. Normal Ants are to seek out other Normal Ants that are closest to them and both get removed from the world when they touch.
Super_Hippo Super_Hippo

2017/4/4

#
Actor nearestAnt=null; double distance=1000000;
for (Object obj : getWorld().getObjects(Ant.class))
{
    if (obj == this) continue;
    Actor ant = (Actor) obj;
    double dist = Math.sqrt(Math.pow(ant.getX()-getX(),2)+Math.pow(ant.getY()-getY(),2));
    if (dist < distance)
    {
        nearestAnt = ant;
        distance = dist;
    }
}

if (nearestAnt != null)
{
    turnTowards(nearestAnt.getX(), nearestAnt.getY());
}
else
{
    //turn randomly, only happens if there is exactly one ant in the world
}
move(2);

if (isTouching(Ant.class))
{
    removeTouching(Ant.class);
    getWorld().removeObject(this);
}
This should work, but the it won't take long until all ants (or all except one) are eliminated.
You need to login to post a reply.
1
2