Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support rotated sprites (and rotated hit boxes) #255

Merged
merged 6 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions backends/bevy_picking_sprite/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,20 +73,28 @@ pub fn sprite_picking(
if blocked || !visibility.is_visible() {
return None;
}
let (scale, _rot, position) = sprite_transform.to_scale_rotation_translation();

// Hit box in sprite coordinate system
let extents = sprite
.custom_size
.or_else(|| images.get(image).map(|f| f.size()))?
* scale.truncate();
let center = position.truncate() - (sprite.anchor.as_vec() * extents);
.or_else(|| images.get(image).map(|f| f.size()))?;
let center = -sprite.anchor.as_vec() * extents;
let rect = Rect::from_center_half_size(center, extents / 2.0);

let is_cursor_in_sprite = rect.contains(cursor_pos_world);
// Transform cursor pos to sprite coordinate system
let cursor_pos_sprite = sprite_transform
.affine()
.inverse()
.transform_point3((cursor_pos_world, 0.0).into());

let is_cursor_in_sprite = rect.contains(cursor_pos_sprite.truncate());
blocked = is_cursor_in_sprite
&& sprite_focus.map(|p| p.should_block_lower) != Some(false);

is_cursor_in_sprite
.then_some((entity, HitData::new(cam_entity, position.z, None, None)))
is_cursor_in_sprite.then_some((
entity,
HitData::new(cam_entity, sprite_transform.translation().z, None, None),
))
},
)
.collect();
Expand Down
5 changes: 3 additions & 2 deletions examples/sprite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,9 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
},
texture: asset_server.load("images/boovy.png"),
// 3x3 grid of anchor examples by changing transform
transform: Transform::from_xyz(i * len - len, j as f32 * len - len, 0.0)
.with_scale(Vec3::splat(1.0 + (i - 1.0) * 0.2)),
transform: Transform::from_xyz(i * len - len, j * len - len, 0.0)
.with_scale(Vec3::splat(1.0 + (i - 1.0) * 0.2))
.with_rotation(Quat::from_rotation_z((j - 1.0) * 0.2)),
..default()
});
}
Expand Down
Loading