Skip to content

Instantly share code, notes, and snippets.

@CoffeeVampir3
Last active January 11, 2023 00:53
Show Gist options
  • Save CoffeeVampir3/398a37446f1463aaeebc5eea13511374 to your computer and use it in GitHub Desktop.
Save CoffeeVampir3/398a37446f1463aaeebc5eea13511374 to your computer and use it in GitHub Desktop.
rust drag&drop sprites
fn handle_mouse_interactions(
button_input: Res<Input<MouseButton>>,
windows: Res<Windows>,
mut interactables: Query<(Entity, &mut Interactable)>,
sprites: Query<(Entity, &GlobalTransform), With<Sprite>>,
rapier_context: Res<RapierContext>,
) {
//Sequence note: This happens first because we want to know if the mouse button was released event outside our window.
if button_input.just_released(MouseButton::Left) {
for (ent, mut interactable) in interactables.iter_mut() {
match *interactable {
Interactable::None => (),
Interactable::Hovering => (),
Interactable::Dragging { offset, start_pos } => {
println!("Drag ended {ent:?}.");
*interactable = Interactable::None; //TODO:: Drag ended.
}
Interactable::Returning => (),
}
}
}
let Some(window) = windows.get_primary() else {return;};
let Some(cursor_point_system) = window.cursor_position() else {return;};
let cursor_point_game = helpers::get_window_relative_cursor_pos(&window);
let mut max = f32::NEG_INFINITY;
let mut res: Option<(Entity, &GlobalTransform)> = None;
rapier_context.intersections_with_point(cursor_point_game, QueryFilter::default(), |x| {
let Ok((ent, xform,)) = sprites.get(x) else {return true};
let ord = xform.translation().z;
if ord >= max {
res = Some((ent, xform));
max = ord;
}
true
});
if res.is_none() {
return;
}
let (hit_ent, xform) = res.unwrap();
let Ok((ent, mut interactable)) = interactables.get_mut(hit_ent) else {return};
match *interactable {
Interactable::None => {
//Begin Hovering.
*interactable = Interactable::Hovering; //TODO:: Hover Begin
}
Interactable::Hovering => {
if button_input.just_pressed(MouseButton::Left) {
let position = xform.translation();
let sprite_position = position.truncate();
let cursor_offset = sprite_position - cursor_point_system;
//Begin Drag
println!("Drag started {ent:?}");
*interactable = Interactable::Dragging {
offset: cursor_offset,
start_pos: position,
}; //TODO:: Drag Begin
}
}
Interactable::Dragging { offset, start_pos } => (), //Dragging Action
Interactable::Returning => (),
}
//Second attempt to use iterated iterator.
for (ent, mut iter_interact) in interactables.iter_mut() {
if (*interactable != *iter_interact) {
//do stuff
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment