Search⌘ K
AI Features

Preparing the Entities Field of View

Explore how to implement fields of view for entities in a Rust-based game. Learn to use field of view algorithms, update visibility dynamically, and render only what the player can see. This lesson helps you create efficient visibility mechanics that enhance gameplay and optimize rendering.

Plotting fields of view

There are many different implementations of field of view algorithms, often optimized to the needs of a specific game. bracket-lib includes a relatively simple one based on path tracing. It works by drawing an imaginary circle around the starting point and then plotting a line to each of the points on the circle’s exterior. Each tile encountered along the line is visible, and the line plot stops when it hits an opaque tile, represented by #. The algorithm may be visualized like this:

As a counterpart to the FieldOfView component, we have to create a system to use it and implement the field of view algorithm. Create a new file, systems/fov.rs, and add the following to it:

Rust 1.40.0
use crate::prelude::*;
#[system]
#[read_component(Point)]
#[write_component(FieldOfView)]
pub fn fov(
ecs: &mut SubWorld,
#[resource] map: &Map,
) {
let mut views = <(&Point, &mut FieldOfView)>::query();
views
.iter_mut(ecs)
.for_each(|(pos, mut fov)| {
fov.visible_tiles = field_of_view_set(*pos, fov.radius, map);
fov.is_dirty = false;
}
);
}
  • Line 10: This creates a query that reads the Point component (the entity’s position) and can write to the FieldOfView component.

  • Line 12: This runs the query with iter_mut(), allowing us to change the FieldOfView entries.

  • Line 13: This filters the iterator with a check on the is_dirty field. This ensures that only dirty (entries ...