So I set out to make an entity manager that would allow individual entities search for other entities and get limited amounts of entities for processing, like collision detection. Well here is what I came up with:
package mbs.exodus.managers;
import java.util.ArrayList;
import mbs.exodus.game.entities.Entity;
public class EntityManager
{
public static ArrayList<Entity> entities = new ArrayList<Entity>();
public static void registerEntity(Entity e)
{
if(e != null)
{
entities.add(e);
}
}
public static void removeEntity(Entity e)
{
if(e != null)
{
e.destroy();
entities.remove(e);
}
}
public static Entity[] getEntitiesByOwner(String ownerID)
{
Entity[] e = new Entity[entities.size()];
entities.toArray(e);
return getEntitiesByOwner(ownerID,e);
}
public static Entity[] getEntitiesByOwner(String ownerID, Entity[] sample)
{
ArrayList<Entity> list = new ArrayList<Entity>();
for(Entity e : sample)
{
if(e.getOwnerID().equals(ownerID))
{
list.add(e);
}
}
Entity[] entityArray = new Entity[list.size()];
list.toArray(entityArray);
return entityArray;
}
public static Entity[] getEntitiesByLocation(int x, int y, int radius)
{
Entity[] e = new Entity[entities.size()];
entities.toArray(e);
return getEntitiesByLocation(x,y,radius,e);
}
public static Entity[] getEntitiesByLocation(int x, int y, int radius, Entity[] sample)
{
ArrayList<Entity> list = new ArrayList<Entity>();
for(Entity e : sample)
{
if(Math.abs(Math.sqrt((Math.pow((x - (e.getX() + e.getSizeX()/2)), 2)) +
(Math.pow((y - (e.getY() + e.getSizeY()/2)), 2)))) < radius)
{
list.add(e);
}
}
Entity[] entityArray = new Entity[list.size()];
list.toArray(entityArray);
return entityArray;
}
public static Entity getEntityByClick(int x, int y)
{
Entity entity = null;
for(Entity e : entities)
{
if(x < (e.getX() + e.getSizeX()) && x > e.getX() && y < (e.getY() + e.getSizeY()) && y > e.getY())
{
entity = e;
break;
}
}
return entity;
}
}
So an individual entity can ask the manager for only the entities within firing range for example (no need to do operations on things out of range)
or you can ask for only the entities within visible range, so you only render entities visible on the screen
lot of things you can do…
My only concern is when there are thousands of entities registered with the manager… if asking for limited entity sets every update is actually slower than doing operations and decision logic on all the thousands of entities every update instead. I will only know when I have thousands of entities! haha!
Anyway I thought I would share, and hopefully get some pointers, and maybe inspire someone to climb one step higher in the quest for the perfect entity manager!