This commit is contained in:
Rendo 2026-01-25 04:42:32 +05:00
commit badc59c239
2 changed files with 143 additions and 36 deletions

View file

@ -13,22 +13,53 @@ pub struct Hand;
#[derive(Resource)]
pub struct CardImage(Handle<Image>);
#[derive(Event)]
pub struct AddCard;
#[derive(Event)]
pub struct ClearCards;
impl Plugin for CardPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Startup, (hand_setup, test_card_setup).chain())
.add_systems(Update, card_arrange);
app.add_systems(Startup, hand_setup)
.add_systems(Update, card_arrange)
.add_observer(card_add)
.add_observer(card_clear);
}
}
fn hand_setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn((Hand, Transform::from_xyz(0., -360., 0.)));
commands.spawn((
Hand,
Transform::from_xyz(0., -360., 0.),
InheritedVisibility::VISIBLE,
));
commands.insert_resource(CardImage(
asset_server.load::<Image>("sprites/cards/units/fosma.png"),
));
}
fn test_card_setup(
fn card_arrange(
query: Query<(Entity, &mut Transform, &Sprite, &ChildOf), With<Card>>,
hand: Single<(Entity, &Children), With<Hand>>,
assets: Res<Assets<Image>>,
) {
let cards_amount = hand.1.len();
for (entity, mut transform, sprite, child_of) in query {
if child_of.parent() != hand.0 {
continue;
}
let size = assets.get(&sprite.image).unwrap().size_f32();
let left_boundary = -size.x * (cards_amount as f32) / 2.0 + size.x / 2.0;
transform.translation.x =
left_boundary + size.x * (hand.1.iter().position(|x| x == entity).unwrap_or(0) as f32);
transform.translation.y = size.y / 2.0;
}
}
fn card_add(
_: On<AddCard>,
mut commands: Commands,
hand: Single<Entity, With<Hand>>,
card_image: Res<CardImage>,
@ -39,38 +70,10 @@ fn test_card_setup(
Card,
ChildOf(hand.entity()),
));
commands.spawn((
Sprite::from_image(card_image.0.clone()),
Transform::from_xyz(0., 0., 0.),
Card,
ChildOf(hand.entity()),
));
commands.spawn((
Sprite::from_image(card_image.0.clone()),
Transform::from_xyz(0., 0., 0.),
Card,
ChildOf(hand.entity()),
));
}
fn card_arrange(
query: Query<(&mut Transform, &Sprite, &ChildOf), With<Card>>,
hand: Single<(Entity, &Children), With<Hand>>,
assets: Res<Assets<Image>>,
) {
let cards_amount = hand.1.len();
let mut card_id = 0.;
for (mut transform, sprite, child_of) in query {
if child_of.parent() != hand.0 {
continue;
}
let size = assets.get(&sprite.image).unwrap().size_f32();
let left_boundary = -size.x * (cards_amount as f32) / 2.0 + size.x / 2.0;
transform.translation.x = left_boundary + size.x * card_id;
transform.translation.y = size.y / 2.0;
card_id += 1.0;
fn card_clear(_: On<ClearCards>, mut commands: Commands, children: Single<&Children, With<Hand>>) {
for card in children.iter() {
commands.entity(card).despawn();
}
}