├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── README.md ├── basic_ifthen.rs ├── basic_while.rs ├── bevy_behave_chase_example.png ├── chase.rs └── console_logging.png ├── readme.inc.md ├── readme.sh └── src ├── behave_trigger.rs ├── ctx.rs ├── dyn_bundle.rs ├── lib.rs ├── plugin.rs └── tests.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## unreelased 2 | 3 | * rename `BehaveCtx::elapsed_secs_epoch()` to `BehaveCtx::elapsed_secs()` 4 | 5 | ## 0.3.0 6 | 7 | * bevy 0.16 release -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "bevy_behave" 3 | version = "0.3.0" 4 | edition = "2024" 5 | description = "A behaviour tree plugin for bevy with dynamic spawning." 6 | repository = "https://github.com/RJ/bevy_behave" 7 | documentation = "https://docs.rs/bevy_behave" 8 | keywords = ["bevy", "tree", "ai", "game"] 9 | license = "MIT OR Apache-2.0" 10 | authors = ["Richard Jones "] 11 | 12 | [dependencies] 13 | bevy = {version = "0.16", default-features = false, features = ["bevy_log"]} 14 | dyn-clone = "1.0.18" 15 | ego-tree = "0.10.0" 16 | 17 | [dev-dependencies] 18 | bevy = {version = "0.16", default-features = true} 19 | bevy_screen_diagnostics = "0.8.1" 20 | bevy_pancam = "0.18" 21 | rand = "0.9.0" 22 | 23 | 24 | [lints.clippy] 25 | type_complexity = "allow" 26 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is 8 | furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 19 | SOFTWARE. 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bevy_behave 2 | 3 |
4 |

5 | A behaviour tree plugin for bevy with dynamic spawning. 6 |

7 |

8 | crates.io 9 | docs.rs 10 | discord channel 11 | 12 |

13 |
14 | 15 | `bevy_behave` is a behaviour tree plugin for bevy with a sensible API and minimal overheads. 16 | No magic is required for the task components, they are are regular bevy components using triggers to report status. 17 | 18 | When an action node (aka leaf node or task node) in the behaviour tree runs, it will spawn an entity with 19 | the components you specified in the tree definition. The tree then waits for this entity to 20 | trigger a status report, at which point the entity will be despawned. 21 | 22 | You can also take actions without spawning an entity by triggering an observed `Event`, which can also be used as a conditional in a control node. 23 | 24 | 25 | This tree definition is from the [chase example](https://github.com/RJ/bevy_behave/blob/main/examples/chase.rs): 26 | 27 | ```rust 28 | let npc_entity = get_enemy_entity(); 29 | let player = get_player_entity(); 30 | // The tree definition (which is cloneable). 31 | // and in theory, able to be loaded from an asset file using reflection (PRs welcome). 32 | // When added to the BehaveTree component, this gets transformed internally to hold state etc. 33 | // 34 | // These trees are `ego_tree::Tree` if you want to construct them manually. 35 | // Conventient macro usage shown below. 36 | let tree = behave! { 37 | Behave::Forever => { 38 | Behave::Sequence => { 39 | Behave::spawn(( 40 | Name::new("Wait until player is near"), 41 | WaitUntilPlayerIsNear{player} 42 | )), 43 | Behave::Sequence => { 44 | Behave::spawn(( 45 | Name::new("Move towards player while in range"), 46 | MoveTowardsPlayer{player, speed: 100.0} 47 | )), 48 | // MoveTowardsPlayer suceeds if we catch them, in which randomize our colour. 49 | // This uses a trigger to take an action without spawning an entity. 50 | Behave::trigger(RandomizeColour), 51 | // then have a nap (pause execution of the tree) 52 | // NB: this only runs if the trigger_req was successful, since it's in a Sequence. 53 | Behave::Wait(5.0), 54 | } 55 | } 56 | } 57 | }; 58 | ``` 59 | 60 | 61 |
62 | 63 | You can also compose trees from subtrees 64 | 65 | ```rust 66 | 67 | let npc_entity = get_enemy_entity(); 68 | let player = get_player_entity(); 69 | // Breaking a tree into two trees and composing, just to show how it's done. 70 | let chase_subtree = behave! { 71 | Behave::Sequence => { 72 | Behave::spawn(( 73 | Name::new("Move towards player while in range"), 74 | MoveTowardsPlayer{player, speed: 100.0} 75 | )), 76 | // MoveTowardsPlayer suceeds if we catch them, in which randomize our colour. 77 | // This uses a trigger to take an action without spawning an entity. 78 | Behave::trigger(RandomizeColour), 79 | // then have a nap (pause execution of the tree) 80 | // NB: this only runs if the trigger_req was successful, since it's in a Sequence. 81 | Behave::Wait(5.0), 82 | } 83 | }; 84 | 85 | let tree = behave! { 86 | Behave::Forever => { 87 | // Run children in sequence until one fails 88 | Behave::Sequence => { 89 | // WAIT FOR THE PLAYER TO GET CLOSE 90 | // Spawn with any normal components that will control the target entity: 91 | Behave::spawn(( 92 | Name::new("Wait until player is near"), 93 | WaitUntilPlayerIsNear{player} 94 | )), 95 | // CHASE THE PLAYER 96 | @ chase_subtree 97 | } 98 | } 99 | }; 100 | ``` 101 | 102 |
103 | 104 |
105 | 106 | Once you have your tree definition, you spawn an entity to run the behaviour tree by adding a `BehaveTree` component: 107 | 108 | ```rust 109 | // Spawn an entity to run the behaviour tree. 110 | // Make it a child of the npc entity for convenience. 111 | // The default is to assume the Parent of the tree entity is the Target Entity you're controlling. 112 | commands.spawn(( 113 | Name::new("Behave tree for NPC"), 114 | BehaveTree::new(tree), 115 | ChildOf(npc_entity), 116 | )); 117 | ``` 118 | 119 | If your behaviour tree is not a child of the target entity you want to control, you can specify the target entity explicitly: 120 | 121 | ```rust 122 | let target = get_entity_to_control(); 123 | commands.spawn(( 124 | Name::new("Behave tree for NPC"), 125 | BehaveTree::new(tree), 126 | BehaveTargetEntity::Entity(target), 127 | )); 128 | ``` 129 | 130 | Or in case of a deeper hierarchy, you can use `BehaveTargetEntity::RootAncestor` to find the topmost entity. 131 | 132 | 133 | 134 | ### Control Flow Nodes 135 | 136 | The following control flow nodes are supported. Control flow logic is part of the `BehaveTree` and doesn't spawn extra entities. 137 | 138 | | Node | Description | 139 | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- | 140 | | `Behave::Sequence` | Runs children in sequence, failing if any child fails, succeeding if all children succeed. | 141 | | `Behave::Fallback` | Runs children in sequence until one succeeds. If all fail, this fails. Sometimes called a Selector node. | 142 | | `Behave::Invert` | Inverts success/failure of child. Must only have one child. | 143 | | `Behave::AlwaysSucceed` | Succeeds instantly. | 144 | | `Behave::AlwaysFail` | Fails instantly. | 145 | | `Behave::While` | Runs the second child repeatedly, provided the first child returns success. If only one child, runs it repeatedly until it fails. | 146 | | `Behave::IfThen` | If the first child succeeds, run the second child. (otherwise, run the optional third child) | 147 | 148 | 149 | #### Control Flow Node Examples 150 | 151 | 152 | ##### Sequence 153 | 154 | Use `Behave::Sequence` to run children in sequence, failing if any child fails, succeeding if all children succeed. 155 | 156 | This example runs a trigger (and assuming it reports success..), waits 5 secs, then spawns an entity with an imagined `BTaskComponent` to do something. 157 | 158 | ```rust 159 | let tree = behave! { 160 | Behave::Sequence => { 161 | Behave::trigger(DoA), 162 | Behave::Wait(5.0), 163 | Behave::spawn_named("B-Doer", BTaskComponent::default()), 164 | } 165 | }; 166 | ``` 167 | 168 | 169 | ##### Fallback 170 | 171 | Use `Behave::Fallback` to run children in sequence until one succeeds. If they all fail, the Fallback node also fails. 172 | 173 | ```rust 174 | let tree = behave! { 175 | Behave::Fallback => { 176 | Behave::trigger(TryA), 177 | Behave::trigger(TryB), 178 | Behave::trigger(TryC), 179 | } 180 | }; 181 | ``` 182 | 183 | ##### While (single child usage) 184 | 185 | You can wrap a single node in a `Behave::While` node to repeat it until it fails. 186 | 187 | ```rust 188 | let tree = behave! { 189 | Behave::While => { 190 | Behave::trigger(DoSlowThingUntilFailure), 191 | } 192 | }; 193 | ``` 194 | 195 | ##### While (two child usage) 196 | 197 | With two children, the first child is the conditional check. If it succeeds, the second child is run. And then the node repeats. 198 | 199 | ```rust 200 | let tree = behave! { 201 | Behave::While => { 202 | Behave::trigger(AirbourneCheck), 203 | Behave::spawn_named("Fly!", (FlapWings::default(), PointToes::default())), 204 | } 205 | }; 206 | ``` 207 | 208 | ##### IfThen (two child usage) 209 | 210 | The first child is the conditional check, the second is only run if the condition succeeds. 211 | 212 | ```rust 213 | let tree = behave! { 214 | Behave::IfThen => { 215 | Behave::trigger(HungryCheck), 216 | Behave::Sequence => { 217 | // move to food, but only allow 10 seconds to do so. Then eat, if we got there. 218 | Behave::spawn_named("Go to food", (MoveToFood::default(), BehaveTimeout::from_secs(10.0, false))), 219 | Behave::trigger(EatFood), 220 | }, 221 | } 222 | }; 223 | ``` 224 | 225 | ##### IfThen (three child usage) 226 | 227 | An optional third child acts as the "else" clause, and is run if the conditional fails. 228 | 229 | ```rust 230 | let tree = behave! { 231 | Behave::IfThen => { 232 | Behave::trigger(HungryCheck), 233 | Behave::Sequence => { 234 | Behave::spawn_named("Go to food", (MoveToFood::default(), BehaveTimeout::from_secs(10.0, false))), 235 | Behave::trigger(EatFood), 236 | }, 237 | Behave::trigger(TidyKitchen), 238 | } 239 | }; 240 | ``` 241 | 242 | 243 | ### Task Nodes 244 | 245 | Task nodes are leaves of the tree which take some action, typically doing something to control your target entity, such as making it move. 246 | 247 | ##### Behave::Wait 248 | 249 | Waits a given duration before Succeeding. The timer is ticked by the tree itself, so no entities are spawned. 250 | 251 | ```rust 252 | let tree = behave! { 253 | Behave::Wait(5.0), 254 | }; 255 | ``` 256 | 257 | ##### Behave::spawn(...) and Behave::spawn_named(...) 258 | 259 | When a `Behave::spawn_named` node runs, a new entity is spawned with the bundle of components you provided along with a 260 | `BehaveCtx` component, used to get the target entity the tree is controlling, and the mechanism to generate status reports. 261 | 262 | Once a result is reported, the entity is despawned. 263 | 264 | ```rust 265 | // Flap our wings, and succeed (end the task) after 60 seconds. 266 | let tree = behave! { 267 | Behave::spawn_named("Flying Task", 268 | (WingFlapper::default(), BehaveTimeout::from_secs(60.0, true)) 269 | ) 270 | }; 271 | ``` 272 | 273 | Prefer the `Behave::spawn_named` variant, because in addition to adding a `Name` component to the spawned entity, it exposes this name in debug logging. 274 | 275 |
276 | 277 | An example implementation (click to reveal) 278 | 279 | ```rust 280 | // An example plugin to provide a `WingFlapper` task component. 281 | 282 | fn wing_flapper_task_plugin(app: &mut App) { 283 | app.add_systems(FixedUpdate, wing_flap_system); 284 | } 285 | 286 | #[derive(Component, Clone, Default)] 287 | struct WingFlapper { 288 | speed: f32, 289 | } 290 | 291 | fn wing_flap_system( 292 | mut q_target: Query<&mut Wings, With>, 293 | flapper_tasks: Query<(&WingFlapper, &BehaveCtx)>, 294 | mut commands: Commands 295 | ) { 296 | // for each entity with a WingFlapper component and a BehaveCtx, flap the wings for its target entity 297 | for (flapper, ctx) in flapper_tasks.iter() { 298 | // the target entity is the one being controlled by the behaviour tree that spawned this task entity 299 | let target = ctx.target_entity(); 300 | let Ok(mut target_wings) = q_target.get_mut(target) else { 301 | // Maybe the wings fell off? report task failure. 302 | commands.trigger(ctx.failure()); 303 | continue; 304 | }; 305 | target_wings.flap(flapper.speed); 306 | } 307 | } 308 | ``` 309 |
310 | 311 | 312 | ##### Behave::trigger(...) 313 | 314 | When a `Behave::trigger` node runs, it will trigger an event, which the user observes and can either respond to with a success or failure immediately, or respond later from another system. You must specify an arbitrary `Clone` type which is passed along as 315 | the payload of the trigger event, along with the `BehaveCtx`. 316 | 317 | Here's how you might use a trigger conditional check to execute a specific task if a height condition is met: 318 | 319 | ```rust 320 | let tree = behave! { 321 | Behave::IfThen => { 322 | Behave::trigger(HeightCheck { min_height: 10.0 }), 323 | Behave::spawn_named("High Thing", TakeActionWhenHigh::default()), 324 | } 325 | }; 326 | ``` 327 |
328 | 329 | And the implementation (click to reveal) 330 | 331 | 332 | ```rust 333 | // An example plugin to provide a `HeightCheck` trigger task 334 | 335 | fn height_check_task_plugin(app: &mut App) { 336 | // add a global observer to answer conditional queries for HeightCheck: 337 | app.add_observer(on_height_check); 338 | } 339 | 340 | // Trigger payloads just need to be Clone. 341 | // They are wrapped in a BehaveTrigger, which is a bevy Event. 342 | #[derive(Clone)] 343 | struct HeightCheck { 344 | min_height: f32, 345 | } 346 | 347 | // you respond by triggering a success or failure event created by the ctx: 348 | fn on_height_check(trigger: Trigger>, q: Query<&Position>, mut commands: Commands) { 349 | let ev = trigger.event(); 350 | let ctx: &BehaveCtx = ev.ctx(); 351 | let height_check: &HeightCheck = ev.inner(); 352 | // lookup the position of the target entity (ie the entity this behaviour tree is controlling) 353 | let character_pos = q.get(ctx.target_entity()).expect("Character entity missing?"); 354 | if character_pos.y >= height_check.min_height { 355 | commands.trigger(ctx.success()); 356 | } else { 357 | commands.trigger(ctx.failure()); 358 | } 359 | } 360 | 361 | ``` 362 |
363 | 364 |
365 | 366 | If you respond with a success or failure from the observer you can treat the event as a conditional test as part of a control flow node. Alternatively, you can use it to trigger a side effect and respond later from another system. Just make sure to copy the `BehaveCtx` so you can generate a success or failure event at your leisure. 367 | 368 | 369 | 370 | ### Cargo Example 371 | 372 | Have a look at the [chase example](https://github.com/RJ/bevy_behave/blob/main/examples/chase.rs) to see how these are used. 373 | Run in release mode to support 100k+ enemies at once: 374 | ```bash 375 | cargo run --release --example chase 376 | ``` 377 | 378 | 379 | ### Utility components 380 | 381 | For your convenience: 382 | 383 | ##### Triggering completion after a timeout 384 | 385 | To trigger a status report on a dynamic spawn task after a timeout, use the `BehaveTimeout` helper component: 386 | 387 | ```rust 388 | let tree = behave! { 389 | Behave::spawn_named("Long running task that succeeds after 5 seconds", ( 390 | LongRunningTaskComp::default(), 391 | BehaveTimeout::from_secs(5.0, true) 392 | )) 393 | }; 394 | ``` 395 | 396 | This will get the `BehaveCtx` from the entity, and trigger a success or failure report for you after the timeout. 397 | 398 | 399 | 400 | ### `behave!` macro 401 | 402 | The `behave!` macro is more powerful version of the `ego_tree::tree!` macro. 403 | You can use ego_tree's `tree!` macro to build the tree, but this macro has some additional features 404 | to make composing behaviours easier: 405 | 406 | ##### Merging in subtrees: 407 | 408 | Use `@` to insert a subtree into the current tree: 409 | ```rust 410 | #[derive(Clone)] 411 | struct A; 412 | #[derive(Clone)] 413 | struct B; 414 | fn get_tree() -> Tree { 415 | let subtree = behave! { 416 | Behave::Sequence => { 417 | Behave::trigger(A), 418 | Behave::Wait(1.0), 419 | Behave::trigger(B), 420 | } 421 | }; 422 | 423 | behave! { 424 | Behave::Sequence => { 425 | Behave::Wait(5.0), 426 | @ subtree 427 | } 428 | } 429 | } 430 | ``` 431 | 432 | Use `...` to insert multiple subtrees from an iterator of trees: 433 | ```rust 434 | #[derive(Clone)] 435 | struct A; 436 | #[derive(Clone)] 437 | struct B; 438 | fn get_tree() -> Tree { 439 | let subtrees = [ 440 | behave! { Behave::Wait(1.0) }, 441 | behave! { Behave::Wait(2.0) }, 442 | behave! { Behave::Wait(3.0) }, 443 | ]; 444 | 445 | behave! { 446 | Behave::Sequence => { 447 | Behave::Wait(5.0), 448 | ... subtrees 449 | } 450 | } 451 | } 452 | ``` 453 | 454 | 455 | ##### Inserting nodes from an iterator: 456 | 457 | Use `@[ ]` to insert leaf nodes (`Behave` enum type, not a tree) from an iterator: 458 | ```rust 459 | #[derive(Clone)] 460 | struct A; 461 | #[derive(Clone)] 462 | struct B; 463 | fn get_tree() -> Tree { 464 | let children = vec![ 465 | Behave::trigger(A), 466 | Behave::Wait(1.0), 467 | Behave::trigger(B), 468 | ]; 469 | behave! { 470 | Behave::Sequence => { 471 | @[ children ] 472 | } 473 | } 474 | } 475 | ``` 476 | 477 | ### Debug Logging 478 | 479 | Call `BehaveTree::with_logging(true)` to enable debug verbose logging: 480 | 481 | ```rust 482 | 483 | let tree = behave! { Behave::Wait(5.0) }; // etc 484 | 485 | commands.spawn(( 486 | Name::new("Behave tree for NPC"), 487 | BehaveTree::new(tree).with_logging(true), 488 | )); 489 | ``` 490 | 491 | 492 | 493 | ### Performance 494 | 495 | is good. 496 | 497 | * There's just one global observer for receiving task status reports from entities or triggers. 498 | * Most of the time, the work is being done in a spawned entity using one of your action components, 499 | and in this state, there is a marker on the tree entity so it doesn't tick or do anything until 500 | a result is ready. 501 | * Avoided mut World systems – the tree ticking should be able to run in parallel with other things. 502 | * So a fairly minimal wrapper around basic bevy systems. 503 | 504 | In release mode, i can happily toss 100k enemies in the chase demo and zoom around at max framerate. 505 | It gets slow rendering a zillion gizmo circles before any bevy_behave stuff gets in the way. 506 | 507 | **Chase example** 508 | 509 | This is the chase example from this repo, running in release mode on an M1 mac with 100k enemies. 510 | Each enemy has a behaviour tree child and an active task component entity. So 1 enemy is 3 entities. 511 | 512 | https://github.com/user-attachments/assets/e12bc4dd-d7fb-4eca-8810-90d65300776d 513 | 514 | **Video from my space game** 515 | 516 | Here I have more complex behaviour trees managing orbits, landing, etc. Lots of PID controllers at work. 517 | No attempts at optimising the logic yet, but I can add 5k ships running behaviours. Each is a dynamic avian physics object exerting forces via a thruster. 518 | 519 | 520 | 521 | 522 | https://github.com/user-attachments/assets/ef4f0539-0b4d-4d57-9516-a39783de140f 523 | 524 | 525 | ### Bevy Version Compatibility 526 | 527 | | bevy_behave | bevy | 528 | | ----------- | ---- | 529 | | 0.3 | 0.16 | 530 | | 0.2.2 | 0.15 | 531 | 532 | 533 | ### Chat / Questions? 534 | 535 | Say hi in the [bevy_behave discord channel](https://discord.com/channels/691052431525675048/1347180005104422942). 536 | 537 | ### Further Reading 538 | 539 | * Cool interactive blog post using bevy_behave: https://www.hankruiger.com/posts/bevy-behave/ 540 | * [Wikipedia on Behavior Trees](https://en.wikipedia.org/wiki/Behavior_tree_(artificial_intelligence,_robotics_and_control)) 541 | 542 | 543 | ### License 544 | 545 | Same as bevy: MIT or Apache-2.0. 546 | 547 |
548 | 549 | 550 | ##### Paths not taken 551 | 552 |
553 | 554 | Alternative approach taking `IntoSystem` (not taken) 555 | 556 | #### Alternative approach for conditionals 557 | 558 | I considered doing control flow by taking an `IntoSystem` with a defined In and Out type, 559 | something like this: 560 | ```rust 561 | 562 | pub type BoxedConditionSystem = Box, Out = bool>>; 563 | 564 | #[derive(Debug)] 565 | pub enum Behave { 566 | // ... 567 | /// If, then 568 | Conditional(BoxedConditionSystem), 569 | } 570 | 571 | impl Behave { 572 | pub fn conditional(system: impl IntoSystem, bool, Marker>) -> Behave { 573 | Behave::Conditional(Box::new(IntoSystem::into_system(system))) 574 | } 575 | } 576 | ``` 577 | 578 | Then you could defined a cond system like, which is quite convenient: 579 | 580 | ```rust 581 | fn check_distance(In(ctx): In, q: Query<&Position, With>) -> bool { 582 | let Ok(player_pos) = q.get(ctx.target_entity).unwrap(); 583 | player_pos.x < 100.0 584 | } 585 | ``` 586 | 587 | 588 | However I don't think the resulting data struct would be cloneable, nor could you really read 589 | it from an asset file for manipulation (or can you?) 590 | 591 | I would also need mutable World in the "tick trees" system, which would stop it running in parallel maybe. 592 | Anyway observers seem to work pretty well. 593 |
594 | 595 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # bevy_behave examples 2 | 3 | ## Chase 4 | 5 | Each enemy entity gets a BehaveTree child entity. and in the normal case, those entities are using 6 | another entity to run the `WaitUntilPlayerIsNear` behaviour. **So 1 enemy = 3 entities.** 7 | 8 | Use **release mode** if you want to spawn lots of enemies at once! 9 | 10 | 11 |
12 | cargo run --release --example chase
13 | 
14 | 15 | -------------------------------------------------------------------------------- /examples/basic_ifthen.rs: -------------------------------------------------------------------------------- 1 | use bevy::{log::LogPlugin, prelude::*}; 2 | use bevy_behave::prelude::*; 3 | 4 | /// ask BehaveTree to log transitions 5 | const ENABLE_LOGGING: bool = true; 6 | 7 | fn main() { 8 | let mut app = App::new(); 9 | app.add_plugins(MinimalPlugins); 10 | app.add_plugins(LogPlugin::default()); 11 | app.add_plugins(BehavePlugin::default()); 12 | app.add_systems(Startup, init); 13 | app.add_observer(on_my_if_condition); 14 | app.add_observer(on_my_then_action); 15 | app.add_observer(on_my_else_action); 16 | app.add_systems( 17 | Update, 18 | delayed_report.run_if(resource_exists::), 19 | ); 20 | app.run(); 21 | } 22 | 23 | #[derive(Resource)] 24 | struct DelayedReporter(f32, BehaveCtx); 25 | 26 | fn delayed_report(dr: Res, mut commands: Commands, time: Res