Player can move and has a sprite

This commit is contained in:
JP Stringham
2026-02-07 19:38:37 -05:00
parent 25c7fa695a
commit 406042ad1f
2 changed files with 53 additions and 7 deletions

View File

@@ -114,6 +114,10 @@ fn levelload(
let parsnip = assets.load("parsnip.png");
// create map from lvl data
let flowerguy = assets.load("flowerfriend.png");
let fl_ta_layout = TextureAtlasLayout::from_grid(uvec2(16, 16), 5, 1, None, None);
let fl_ta_handle = ta_layouts.add(fl_ta_layout);
let lvl = &lvl.ldtk_proj.levels[0];
let mut lyr_dep = 50f32;
@@ -153,9 +157,18 @@ fn levelload(
));
match ei.identifier.as_str() {
"Player" => {
spawned_ent.insert(Player {});
spawned_ent.insert(PhysicsBody2D { pos, ..default() });
spawned_ent.insert(Sprite::from_color(Color::WHITE, vec2(16., 16.)));
spawned_ent.insert(Player::default());
spawned_ent.insert(PhysicsBody2D {
pos: pos * UNITS_TO_PX_SCALE,
..default()
});
spawned_ent.insert(Sprite::from_atlas_image(
flowerguy.clone(),
TextureAtlas {
layout: fl_ta_handle.clone(),
index: 0,
},
));
}
"Parsnip" => {
spawned_ent.insert(Sprite::from_image(parsnip.clone()));
@@ -173,7 +186,8 @@ fn levelload(
fn gameloop(
keyb: Res<ButtonInput<KeyCode>>,
mut player_sing: Single<(&mut PhysicsBody2D, &mut Transform), With<Player>>,
mut player_sing: Single<(&mut PhysicsBody2D, &mut Transform, &mut Player, &mut Sprite)>,
time: Res<Time>,
) {
let mut dir = I64Vec2::ZERO;
@@ -207,8 +221,36 @@ fn gameloop(
play_phys.tick();
*player_sing.1 = Transform::from_xyz(
(play_phys.pos.x as f32) / UNITS_TO_PX_SCALE as f32,
(play_phys.pos.y as f32) / UNITS_TO_PX_SCALE as f32,
(play_phys.pos.x / UNITS_TO_PX_SCALE) as f32,
(play_phys.pos.y / UNITS_TO_PX_SCALE) as f32,
100.,
);
let plyr = player_sing.2.as_mut();
if time.elapsed_secs_f64() - plyr.last_frame > 0.1 {
plyr.last_frame = time.elapsed_secs_f64();
if dir.length_squared() > 0 {
plyr.anim_index = (plyr.anim_index + 1) % 5;
} else {
plyr.anim_index = 0;
}
}
if dir.x > 0 {
plyr.flip = true;
} else if dir.x < 0 {
plyr.flip = false;
}
let flip = plyr.flip;
let anim_index = plyr.anim_index;
let spr = player_sing.3.as_mut();
spr.flip_x = flip;
if let Some(atlas) = &mut spr.texture_atlas {
atlas.index = anim_index;
}
}

View File

@@ -1,4 +1,8 @@
use bevy::ecs::component::Component;
#[derive(Default, Debug, Component)]
pub struct Player {}
pub struct Player {
pub last_frame: f64,
pub anim_index: usize,
pub flip: bool,
}