Skip to main content

bevy_magic/
ext.rs

1use std::sync::Arc;
2
3use bevy::prelude::*;
4
5use crate::{
6    enchanting::{ApplyEnchantmentMessage, Enchantment, RemoveEnchantmentMessage, TriggerEnchantmentMessage},
7    CastSpellMessage, Spell,
8};
9
10pub trait CommandsExt {
11    /// Cast a spell from `caster` at optional `targets`.
12    fn cast_magic(
13        &mut self,
14        caster: Entity,
15        spell: Handle<Spell>,
16        targets: Option<Vec<Entity>>,
17    ) -> &mut Self;
18
19    /// Apply `enchantment` to `target`. The target must have the [`crate::enchanting::Enchantable`] component.
20    fn apply_enchantment(&mut self, target: Entity, enchantment: Enchantment) -> &mut Self;
21
22    /// Remove the enchantment named `name` from `target`.
23    fn remove_enchantment(&mut self, target: Entity, name: impl Into<String>) -> &mut Self;
24
25    /// Manually fire the runes enchantment named `name` on `source`, affecting `targets`.
26    fn trigger_enchantment(
27        &mut self,
28        source: Entity,
29        name: impl Into<String>,
30        targets: Option<Vec<Entity>>,
31    ) -> &mut Self;
32}
33
34impl CommandsExt for Commands<'_, '_> {
35    fn cast_magic(
36        &mut self,
37        caster: Entity,
38        spell: Handle<Spell>,
39        targets: Option<Vec<Entity>>,
40    ) -> &mut Self {
41        self.write_message(CastSpellMessage {
42            caster,
43            targets: targets.unwrap_or_else(Vec::new),
44            spell,
45        })
46    }
47
48    fn apply_enchantment(&mut self, target: Entity, enchantment: Enchantment) -> &mut Self {
49        self.write_message(ApplyEnchantmentMessage {
50            target,
51            enchantment: Arc::new(enchantment),
52        })
53    }
54
55    fn remove_enchantment(&mut self, target: Entity, name: impl Into<String>) -> &mut Self {
56        self.write_message(RemoveEnchantmentMessage {
57            target,
58            name: name.into(),
59        })
60    }
61
62    fn trigger_enchantment(
63        &mut self,
64        source: Entity,
65        name: impl Into<String>,
66        targets: Option<Vec<Entity>>,
67    ) -> &mut Self {
68        self.write_message(TriggerEnchantmentMessage {
69            source,
70            name: name.into(),
71            targets: targets.unwrap_or_else(Vec::new),
72        })
73    }
74}