#Having trouble grasping the basics of the ECS

18 messages · Page 1 of 1 (latest)

gritty venture
#

I haven't actually coded anything yet and am just trying to grasp it as a concept, sorry if it's a dumb question
Stumbled upon Bevy and ECS recently as someone that only briefly worked with Unity (very briefy, nothing more than platformer protoypes lol) and I'm stumped grasping it.

I understand the basic concept of decoupling everything to keep code clean, organised and perfomant, but how do things that need to be coupled.. work? Say I want the camera to shake when an enemy dies - won't the whole point of ECS go down the drain the moment I make the enemy interact with the camera even though it was the player that did something?

I may be reading too into it aha... sorry

night zodiac
#

i would have two systems, one that sends an event called CameraShake, and one that receives that event. That way, the system that handles the shaking of the camera is decoupled from the other system. You can more systems that could shake the camera, like for example taking fall damage or whatever, by creating more event writers, and simply schedule the system accordingly.

gritty venture
#

Ohh that seems really neat! How would the implementation actually work though? Maybe it's because I'm a beginner aha but how would the event spawners be "wired up" to the receivers in a generic way and such? Sorry for bothering again

outer verge
#
fn death_system(
  mut death_events: EventWriter<DeathEvent>,
  query: Query<(Entity, &HitPoints), With<Enemy>>
) {
  query.for_each(|(enemy_id, hp)| {
    if hp.value <= 0 {
      death_events.send(DeathEvent(enemy_id));
    }  
  });
}

fn shake_camera_on_enemy_death_system(
  mut death_events: EventReader<DeathEvent>,
  enemy_query: Query<Entity, With<Enemy>>,
  camera_query: Query<(&Camera, &mut Transform)>,
) {
for death_event in death_events.iter() {
  if enemy_query.get(death_event.0).is_ok() {
    // code to move the camera about or something here
  }
}
}
#

something like that

#

that code may not work as I just made it up on the spot but

night zodiac
outer verge
#

ah

#

thats not a problem

#

any system can subscribe to the death events

#

you could also have like

#
fn explode_enemy_system(
  mut death_events: EventReader<DeathEvent>,
  ...
) {
  for death_events in death_events.iter() {
    // spawn an explosion or something where enemy the died
  }
}
#

so like now

#

if you dispatch the DeathEvent from the death_system

#

both the camera_shake_system and explode_enemy_systems will recieve the DeathEvent

night zodiac
#

imo i would have two events, one for camera shake and one for exploding enemies so that these two impl are decoupled at least

#

but yeah that is how we usually deal with events

gritty venture
#

You did not need to go through the trouble of writing that, it was just an example.. thank you!