Crates.io | bevy_cursor_hovering_sprite |
lib.rs | bevy_cursor_hovering_sprite |
version | 0.2.0 |
source | src |
created_at | 2024-05-30 14:21:20.600707 |
updated_at | 2024-06-20 06:47:31.276918 |
description | a very lightweight plugin for bevy engine to check if a cursor is hovering on one 2d sprite |
homepage | |
repository | https://github.com/xavierwoo/bevy_cursor_hovering_sprite |
max_upload_size | |
id | 1256916 |
size | 9,912 |
Here is a very lightweight plugin for bevy engine to check if a cursor is hovering on one 2d sprite.
bevy | bevy_cursor_hovering_sprite |
---|---|
0.13 | ^0.1.0 |
When adding this plugin to your bevy project and attaching a SpriteBorder component to one entity (may be a sprite), this plugin checks if the cursor is currently hovering in the region defined by the SpriteBorder and the entity's coordinate. If the cursor is hovering on one entity, the plugin emits an event CursorOnSprite, reporting the entity.
It can be used to implement a 2d sprite picking funtionality.
Check the example folder to see how to use it.
The idea is simple. First translate the cursor position into the 2d world coordinate. And then check whether this coordinate resides in the polygon calculated from the SpriteBorder component and the entity's world coordinate.
I drew lessons from https://www.geeksforgeeks.org/how-to-check-if-a-given-point-lies-inside-a-polygon/ to check whether a point is inside a polygon.
To save the energy, only entities visible in the camera is checked by iterating through VisibleEntities.
When adding this plugin, the following things will be added to your project:
#[derive(Resource)]
pub struct CursorHoveringCamera{
pub entity: Option<Entity>,
}
#[derive(Asset, TypePath, Debug)]
pub struct BorderPolygon{
pub points: Vec<Vec2>,
}
#[derive(Component)]
pub struct SpriteBorder{
pub polygon: Handle<BorderPolygon>,
}
#[derive(Event)]
pub struct CursorOnSprite{
pub entity: Entity,
}
#[derive(States, Debug, Clone, Copy, Eq, PartialEq, Hash, Default)]
pub enum CursorHoveringSpriteState{
#[default]
Checking,
Idling,
}
fn cursor_hovering(
window_query: Query<&Window>,
camera_query: Query<(&Camera, &GlobalTransform)>,
visible_entities_query: Query<&VisibleEntities>,
sprite_query: Query<(&Transform, &SpriteBorder)>,
border_asset: Res<Assets<BorderPolygon>>,
picking_camera: Res<CursorHoveringCamera>,
mut cursor_on_event_writer: EventWriter<CursorOnSprite>,
){/*...*/}