...

/

Implementing Combat

Implementing Combat

Learn how to attack monsters and how health bars and monsters’ tooltips will show damage.

Combat plays a large part in most games, so it’s worth the effort to develop a flexible system. We now have all of the elements required to implement combat. Monsters and the adventurer have health, we know where they are, and we’re displaying the results. Let’s implement bump-to-attack melee combat.

Remove the collision system

Start by removing the existing collision system. It served its purpose, but we need something more advanced to handle combat.

Remove the systems/collision.rs file and remove all references to it, and then call the collision system in systems/mod.rs.

Indicating intent to attack

The WantsToMove component indicates that an entity intends to move into a tile. We can indicate that an entity wishes to attack another entity similarly by creating a WantsToAttack component. Add the new component type in components.rs:

Press + to interact
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WantsToAttack {
pub attacker : Entity,
pub target : Entity
}

The component stores both the attacker and the target as Entity types. We’ll need to track the attacker later when we start offering rewards for slaying monsters.

Player move to attack

We determine the destination tile as before, but we should now check the destination tile for monsters, rather than blindly issuing a move instruction. If a monster is present, we issue an attack order.

Let’s refactor the player_input system to use the new approach. The start of the system can stay the same; it does what we need.

The first refactor replaces the players iterator. We’ll need a copy of the destination and player entity, so it’s a good idea to obtain them efficiently upfront:

Press + to interact
let (player_entity, destination) = players
.iter(ecs)
.find_map(|(entity, pos)| Some((*entity, *pos + delta)) )
.unwrap();

This is similar to code we’ve written before and uses some Rust tricks for brevity. player_entity and ...