Composing the Player

Hands-on Rust — by Herbert Wolverson (54 / 120)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Installing and Using Legion | TOC | Managing Complexity with Systems 👉

Rather than coding everything player related into a single module, the ECS approach is to describe a player in terms of what components they use. Looking at the Player module from the previous chapter, you can deduce some components that meet your needs:

  • A Player component indicating that the player is a Player. Components don’t have to contain any fields. An empty component is sometimes called a “tag” — it serves to flag that a property exists.
  • A Render component describing how the player appears on the screen.
  • A Position component indicating where the entity is on the map. The Point structure from bracket-lib is ideal for this; it contains an x and a y component, and it also provides several point-related math functions that will prove useful.

Create a new file, src/components.rs. This creates a new module named components. You’re going to use components throughout your game, so it makes sense to add it to your prelude in main.rs:

​ ​mod​ components;
​ ​mod​ prelude {
​ ...
​ ​pub​ ​use​ ​crate​::​components​::*;
​ }

Legion components are usually structs, but can also be enum types such as options. They don’t have to derive any functionality, but when you can, it’s a good idea to derive Clone. This allows you to make a copy of the…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.