Adding a tail

This commit is contained in:
Timothy Warren 2020-12-30 10:10:39 -05:00
parent 19aa9b8d1a
commit 529fe3f2b1

View File

@ -30,11 +30,17 @@ struct SnakeHead {
} }
struct Materials { struct Materials {
head_material: Handle<ColorMaterial>, head_material: Handle<ColorMaterial>,
segment_material: Handle<ColorMaterial>,
food_material: Handle<ColorMaterial>, food_material: Handle<ColorMaterial>,
} }
struct SnakeMoveTimer(Timer); struct SnakeMoveTimer(Timer);
struct SnakeSegment;
#[derive(Default)]
struct SnakeSegments(Vec<Entity>);
struct Food; struct Food;
struct FoodSpawnTimer(Timer); struct FoodSpawnTimer(Timer);
@ -66,11 +72,17 @@ fn setup(commands: &mut Commands, mut materials: ResMut<Assets<ColorMaterial>>)
commands.spawn(Camera2dBundle::default()); commands.spawn(Camera2dBundle::default());
commands.insert_resource(Materials { commands.insert_resource(Materials {
head_material: materials.add(Color::rgb(0.7, 0.7, 0.7).into()), 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()), food_material: materials.add(Color::rgb(1.0, 0.0, 1.0).into()),
}); });
} }
fn spawn_snake(commands: &mut Commands, materials: Res<Materials>) { fn spawn_snake(
commands: &mut Commands,
materials: Res<Materials>,
mut segments: ResMut<SnakeSegments>,
) {
segments.0 = vec![
commands commands
.spawn(SpriteBundle { .spawn(SpriteBundle {
material: materials.head_material.clone(), material: materials.head_material.clone(),
@ -80,8 +92,34 @@ fn spawn_snake(commands: &mut Commands, materials: Res<Materials>) {
.with(SnakeHead { .with(SnakeHead {
direction: Direction::Up, direction: Direction::Up,
}) })
.with(SnakeSegment)
.with(Position { x: 3, y: 3 }) .with(Position { x: 3, y: 3 })
.with(Size::square(0.8)); .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<ColorMaterial>,
position: Position,
) -> Entity {
commands
.spawn(SpriteBundle {
material: material.clone(),
..Default::default()
})
.with(SnakeSegment)
.with(position)
.with(Size::square(0.65))
.current_entity()
.unwrap()
} }
fn snake_movement( fn snake_movement(
@ -186,10 +224,8 @@ fn main() {
height: 500.0, height: 500.0,
..Default::default() ..Default::default()
}) })
.add_resource(SnakeMoveTimer(Timer::new( .add_resource(SnakeMoveTimer(Timer::new(Duration::from_millis(150), true)))
Duration::from_millis(150), .add_resource(SnakeSegments::default())
true,
)))
.add_startup_system(setup.system()) .add_startup_system(setup.system())
.add_startup_stage("game_setup", SystemStage::single(spawn_snake.system())) .add_startup_stage("game_setup", SystemStage::single(spawn_snake.system()))
.add_system(snake_movement.system()) .add_system(snake_movement.system())