7 releases

new 0.15.1-alpha7 Jan 20, 2025
0.15.1-alpha3 Jan 19, 2025

#177 in Game dev

Download history 114/week @ 2025-01-13

121 downloads per month

MIT license

215KB
2K SLoC

Contributors Forks Stargazers Issues MIT License


Logo

bevy_quadtree

A quadtree plugin for Bevy
Explore the docs »

View Demo · Report Bug · Request Feature

Table of Contents
  1. About The Project
  2. Usage
  3. Roadmap
  4. Contributing
  5. License
  6. Contact
  7. Acknowledgments

About The Project

Product Name Screen Shot

A quadtree plugin for bevy.

Function:

  • Auto update following Changed<GlobalTransform>, all users need to do is querying.
  • LooseQuadTree supported.
  • Compile time optimized with const type parameters.

Features:

  • gizmos: show gizmos of the quadtree boundaries.
  • sprite: enable CollisionRect and CollisionRotatedRect to track sprite.custom_size.

(back to top)

Built With

  • Rust
  • Bevy

(back to top)

Usage

  1. Add the plugin to your Cargo.toml:
[dependencies]
bevy_quadtree = { version = "0.15.1" }
  1. Add the plugin to your Bevy app:
# use bevy_app::prelude::*;
# use bevy_transform::prelude::*;
# #[cfg(feature = "sprite")]
# use bevy_sprite::Sprite;
use bevy_quadtree::{QuadTreePlugin, CollisionCircle, CollisionRect};

fn main() {
    #[cfg(feature = "sprite")]
    App::new()
        .add_plugins(QuadTreePlugin::<(
                (CollisionCircle, GlobalTransform), (CollisionRect, (GlobalTransform, Sprite)),
            ),
            40, 100, 100, 20>::default()
        )
        // CollisionCircle follows GlobalTransform, CollisionRect follows Sprite and GlobalTransform
        // at most 40 entities in a node
        // 100 x 100 world size
        // 20 / 10 = 2 = outlet_boundary / inlet_boundary (for loose quadtree)
        .run();
}
  1. Spawn CollisionShapes as Components:
// in systems
cmds.spawn((
    Sprite {
        color: Color::WHITE,
        custom_size: Some(CUSTOM_SIZE),
        ..Default::default()
    },
    // Spawn collision shape `CollisionRect` with `Sprite`,
    // the plugin will auto-update it following `Changed<GlobalTransform>` and `Changed<Sprite>`
    CollisionRect::from(Rect::from_center_size(pos, CUSTOM_SIZE)),
    Transform::from_xyz(pos.x, world_pos.y, 1.),
))
  1. Query the quadtree like bevy's Or, Not:
type MyQuadTree = QuadTree<40, 100, 100, 20>;

fn pick(
    mut gizmos: Gizmos,
    btn: Res<ButtonInput<MouseButton>>,
    key: Res<ButtonInput<KeyCode>>,
    quadtree: Res<MyQuadTree>,
    mut start: Local<Option<Vec2>>,
    ...
) {
    if !btn.pressed(MouseButton::Left) {
        *start = None;
        return;
    }
    let world_position = ...;
    let cancel_pick = key.any_pressed([KeyCode::ShiftLeft, KeyCode::ShiftRight]);
    match *start {
        Some(start) => {
            gizmos.rect_2d(
                (start + world_pos) / 2.,
                (start - world_pos).abs(),
                if cancel_pick { RED } else { WHITE },
            );
            let res = if start.x > world_pos.x {
                // left pick
                quadtree.query::<QOr<(Overlap, Contain)>>(&CollisionRect::from(
                    Rect::from_corners(start, world_pos),
                ))
            } else {
                // right pick
                quadtree
                    .query::<Contain>(&CollisionRect::from(Rect::from_corners(start, world_pos)))
            };
            if cancel_pick {
                ...
            } else {
                ...
            }
        }
        None => *start = Some(world_pos),
    }
}
  1. However, you may need manually update collision shapes in some case
xx.observe(
    |trigger: Trigger<TextRefreshEvent>,
     mut q_box: Query<(&mut Sprite, &mut CollisionRect)>| {
        if let Ok((mut s, mut c)) = q_box.get_mut(trigger.entity()) {
            let ev = trigger.event();
            let delta = Vec2::new(ev.width * FONT_WIDTH, (ev.height - 1.) * FONT_HEIGHT);
            s.custom_size = Some(CUSTOM_SIZE + delta);
            // the plugin default only track `Changed<GlobalTransform>`
            // without feature `sprite` enabled, you can also do this way.
            c.set_init_size(CUSTOM_SIZE + delta);
        }
    },
)

See this repo graph for more complete examples.

For more details, please refer to the Documentation

(back to top)

Roadmap

  • Feature

See the open issues for a full list of proposed features (and known issues).

(back to top)

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)

License

Distributed under the MIT License. See LICENSE.txt for more information.

(back to top)

Contact

Louis - 836250617@qq.com

Project Link: https://github.com/kingwingfly/bevy_quadtree

(back to top)

Acknowledgments

(back to top)

Dependencies

~19–54MB
~895K SLoC