References between Components

(Neidhart Orlich) #1

Hi!
I am new to Rust and decided to learn the language by implementing a simple game with amethyst. I read the book and I believe I understand basic ownership rules. This is btw also my first time using an ECS.

The question is probably really basic, but I just can’t figure it out.

My game is a simple board game on a chessboard. On the board, there are 64 squares. There can be a piece on each of these squares.

I register a square entity like that in the world:

world
                .create_entity()
                .with(square)
                .with(sprite.clone())
                .with(transform)
                .with(coordinates)

Now one rule of the game is that a piece can be moved to its neighboring square. But that’s the tricky thing. How can a square know its neighboring square? I can’t reference it directly because the ECS owns all squares and I can’t borrow it after I pass it to the world.

The only solution I can imagine is to collect a list of all squares every time I want to move a piece within the run method of the piece moving system and calculate the neighboring squares by comparing their coordinates. As I would have to do this every single time from scratch and can’t cache the result because again I can’t save references to the components because the ECS owns the components I am afraid that’s not very efficient.

How would you solve this problem? And even if it wasn’t the solution - is it In any way possible that components - especially components of the same type - reference each other or that there would be a long living outside (non ECS) instance (i.e. the cache) that references a component?

Also, is this the right place to ask a question about this topic? If there is a better place, I will move my question of course there.

Thank you

#2

Not everything is fit for ECS structure, spatial lookup is one of those things. That’s why you have resources where you can store such things. So for example you could have a board resource with 8x8 array, where each item is either None or Some(Entity) (you can use Entity to access its components in systems, it’s like a reference).

1 Like
(Neidhart Orlich) #3

Thanks a lot! I finally got around trying out your suggested solution and it works without any troubles.