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

2016/11/13

getObjectsInRange question

ZoeF ZoeF

2016/11/13

#
Hey all i am curently building a tower defence game. But i am stuck with the getObjectsInRange. While my enemies run over the road the once in a while leave the radius (200) and there fore the list gets changed often. This brings in the problem where enemies who are close to the end do not get targeted. Is there a way to overcome this issue and shoot at the first enemie running on the raod?
danpost danpost

2016/11/13

#
You can have each tower keep an updated list of those in range. Check that against those currently in range. New ones are added to the end of the list and old ones not found currently in range are removed; then, if ready to fire, shoots at the first one in the list.
ZoeF ZoeF

2016/11/13

#
Yeah but then the issue would remain as sometimes the route might take them out of the range and then when it is found again it is added to the back again.
danpost danpost

2016/11/14

#
Okay. Have world create and maintain the list adding when created and added to world and removing any that are removed from the world. Then, have the tower determine the first in the list from what are in range:
// in world
public MyWorld()
{
    super(WIDE, HIGH, 1);
    Tower.enemies = new java.util.ArrayList<Enemies>();
}

@override
public void addObject(Actor actor, int x, int y)
{
    if (actor instanceof Enemies) Tower.enemies.add(actor);
    super.addObject(actor, x, y);
}

@override
public void removeObject(Actor actor)
{
    if (actor instanceof Enemies) Tower.enemies.remove(actor);
    super.removeObject(actor);
}

@override
public void removeObjects(List<Actor> actors)
{
    for (Actor actor : actors) removeObject(actor);
}
// in Towers
import java.util.List;

// class field
public static List<Enemies> enemies;

// in act or called method (after checking if conditions are right to fire a shot)
List<Enemies> closeEnemies = getObjectsInRange(200, Enemies.class);
Enemies enemy = null;
for (enemy : enemies) if (closeEnemies.contains(enemy)) break;
if (enemy != null)  // fire at 'enemy'
This is not tested, but should be close. It is just the idea of how to do it I was working on.
You need to login to post a reply.