From 529fe3f2b1f2eed83a3537913abe31d43658ac28 Mon Sep 17 00:00:00 2001 From: Timothy Warren Date: Wed, 30 Dec 2020 10:10:39 -0500 Subject: [PATCH] Adding a tail --- src/main.rs | 60 ++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 48 insertions(+), 12 deletions(-) diff --git a/src/main.rs b/src/main.rs index c53a652..56e06fb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -30,11 +30,17 @@ struct SnakeHead { } struct Materials { head_material: Handle, + segment_material: Handle, food_material: Handle, } struct SnakeMoveTimer(Timer); +struct SnakeSegment; + +#[derive(Default)] +struct SnakeSegments(Vec); + struct Food; struct FoodSpawnTimer(Timer); @@ -66,22 +72,54 @@ fn setup(commands: &mut Commands, mut materials: ResMut>) commands.spawn(Camera2dBundle::default()); commands.insert_resource(Materials { head_material: materials.add(Color::rgb(0.7, 0.7, 0.7).into()), + segment_material: materials.add(Color::rgb(0.3, 0.3, 0.3).into()), food_material: materials.add(Color::rgb(1.0, 0.0, 1.0).into()), }); } -fn spawn_snake(commands: &mut Commands, materials: Res) { +fn spawn_snake( + commands: &mut Commands, + materials: Res, + mut segments: ResMut, +) { + segments.0 = vec![ + commands + .spawn(SpriteBundle { + material: materials.head_material.clone(), + sprite: Sprite::new(Vec2::new(10.0, 10.0)), + ..Default::default() + }) + .with(SnakeHead { + direction: Direction::Up, + }) + .with(SnakeSegment) + .with(Position { x: 3, y: 3 }) + .with(Size::square(0.8)) + .current_entity() + .unwrap(), + spawn_segment( + commands, + &materials.segment_material, + Position { x: 3, y: 2 }, + ), + ]; +} + +fn spawn_segment( + commands: &mut Commands, + material: &Handle, + position: Position, +) -> Entity { commands .spawn(SpriteBundle { - material: materials.head_material.clone(), - sprite: Sprite::new(Vec2::new(10.0, 10.0)), + material: material.clone(), ..Default::default() }) - .with(SnakeHead { - direction: Direction::Up, - }) - .with(Position { x: 3, y: 3 }) - .with(Size::square(0.8)); + .with(SnakeSegment) + .with(position) + .with(Size::square(0.65)) + .current_entity() + .unwrap() } fn snake_movement( @@ -186,10 +224,8 @@ fn main() { height: 500.0, ..Default::default() }) - .add_resource(SnakeMoveTimer(Timer::new( - Duration::from_millis(150), - true, - ))) + .add_resource(SnakeMoveTimer(Timer::new(Duration::from_millis(150), true))) + .add_resource(SnakeSegments::default()) .add_startup_system(setup.system()) .add_startup_stage("game_setup", SystemStage::single(spawn_snake.system())) .add_system(snake_movement.system())