我正在用 Java 开发一个基本的基于实体组件系统的游戏引擎,以获得乐趣。
我需要一种快速的方法来获取Component
某种类型的所有 s。例子:
public class MovementSystem extends System {
@Override
public void update() {
Set<Location> locations = ComponentManager.getActiveComponents(Location.class);
for (Location locationComponents : locations) {
// do stuff
}
}
}
所以我有一个ComponentManager
应该处理这个的:
public class ComponentManager {
private static final Map<Class<? extends Component>, Set<Component>> active = new HashMap<>();
public static void activate(Component component) {
// if component.class does not have an entry in
// active yet, initialize with new HashSet
active.computeIfAbsent(component.getClass(), compClass -> new HashSet<>());
active.get(component.getClass()).add(component);
}
public static void deactivate(Component component) {
Set<Component> comps = active.get(component.getClass());
if (comps != null)
comps.remove(component);
}
public static <T extends Component> Set<T> getActiveComponents(Class<T> compClass) {
return (Set<T>) active.get(compClass);
}
}
我的 IDE 不喜欢(Set<T>) active.get(compClass);
(以黄色突出显示)。然而,这是基于非常基本的测试,并且比单独铸造每个项目Set
并将它们添加到新的更快Set
,但是这样做的潜在缺点是什么?