How to best structure entities?

I'm trying to set up an ECS for my game. I'm a bit lost as to how an indexing (instead of pointer) system works to look up entities.

In the following small sample (taken from creating ECS) , entities make use of various components as to not have it inside of itself. Therefore any entity can access any component they'd want.

struct PhysicsComponent { ... }
struct HumanoidItemsComponent { ... }
struct HealthComponent { ... }

type EntityIndex = usize;

struct Assets { ... }

struct GameState {
    assets: Assets,

    // All of these component vecs must be the same length, which is the current
    // number of entities.
    physics_components: Vec<Option<PhysicsComponent>>,
    humanoid_items_components: Vec<Option<HumanoidItemsComponent>>,
    health_components: Vec<Option<HealthComponent>>,
    player_components: Vec<Option<PlayerComponents>>,

    players: Vec<EntityIndex>,


Now, I can't figure out how the entities are stored; how do you loop over them? I can see there's an index, so an integer refers to an entity. But how do you make the int EntityIndex greater?
Do you use a function to set it; EntityIndex++?

However that is done, the players are a Vec of integers.
But how do you get the information out of the players Vec? It is just a number.

This is more of a problem for me with Enemies, since I won't be dealing with multiple players. But if I would have a Vec of enemy Indexes, the same would apply. I don't understand how you store the actual data of the Enemy and loop over it efficiently with this system.

If you want to loop over the indexes, skipping the ones that are None, you could do this:

for i in 0..state.physics_components.len() {
    if state.physics_components[i].is_none() { continue; }

Ay. But as I said, I don't even know how best to up the Index..

Since your index type is usize, you can do this:

let new_idx = old_idx + 1;


my_idx += 1;

Ok thanks, pretty simple.

So any idea how to get to the actual data?

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.