Untitled
unknown
java
a year ago
2.4 kB
7
Indexable
// I'm gonna litter this with comments because its a bit complicated. This is how we ensure the player is rendered
// Above or behind objects when it should, dynamically, despite not having a third dimension.
public void updateZIndex() {
entitySubscription = worldEngine.getAspectSubscriptionManager().get(Aspect.all());
List<Entity> entities = new ArrayList<>();
// Fetch all entities that have a PhysicsBodyComponent and ZIndexComponent
IntBag entityIds = entitySubscription.getEntities();
for (int i = 0; i < entityIds.size(); i++) {
entities.add(worldEngine.getEntity(entityIds.get(i)));
}
// Sort entities by Y-position
Collections.sort(entities, new Comparator<Entity>() {
@Override
public int compare(Entity o1, Entity o2) {
// Retrieve the PhysicsBodyComponent & DimensionsComponent for each entity
PhysicsBodyComponent o1BodyComponent = ComponentRetriever.get(o1.getId(), PhysicsBodyComponent.class, worldEngine);
PhysicsBodyComponent o2BodyComponent = ComponentRetriever.get(o2.getId(), PhysicsBodyComponent.class, worldEngine);
// Ensure components exist before trying to access them
if (o1BodyComponent == null || o2BodyComponent == null || o1BodyComponent.body == null || o2BodyComponent.body == null) {
return 0; // Skip comparison if either body is null
}
// Compare the adjusted Y positions of the entities' bodies
return Float.compare(o2BodyComponent.body.getPosition().y, o1BodyComponent.body.getPosition().y);
}
});
// Update the Z-index for each entity based on its position in the sorted list
for (int i = 0; i < entities.size(); i++) {
Entity entity = entities.get(i);
// Retrieve the ZIndexComponent for the entity
ZIndexComponent zIndexComponent = ComponentRetriever.get(entity.getId(), ZIndexComponent.class, worldEngine);
if (zIndexComponent != null) {
zIndexComponent.setZIndex(i);
entity.edit().create(zIndexComponent.getClass()); // Update the entity with the new ZIndexComponent
}
}
}Editor is loading...
Leave a Comment