Growing the snake
This commit is contained in:
parent
962e1bfc12
commit
8a713ba685
50
src/main.rs
50
src/main.rs
@ -36,6 +36,11 @@ struct Materials {
|
||||
|
||||
struct SnakeMoveTimer(Timer);
|
||||
|
||||
struct GrowthEvent;
|
||||
|
||||
#[derive(Default)]
|
||||
struct LastTailPosition(Option<Position>);
|
||||
|
||||
struct SnakeSegment;
|
||||
|
||||
#[derive(Default)]
|
||||
@ -125,6 +130,7 @@ fn spawn_segment(
|
||||
fn snake_movement(
|
||||
keyboard_input: Res<Input<KeyCode>>,
|
||||
snake_timer: ResMut<SnakeMoveTimer>,
|
||||
mut last_tail_position: ResMut<LastTailPosition>,
|
||||
segments: ResMut<SnakeSegments>,
|
||||
mut heads: Query<(Entity, &mut SnakeHead)>,
|
||||
mut positions: Query<&mut Position>,
|
||||
@ -172,7 +178,45 @@ fn snake_movement(
|
||||
.zip(segments.0.iter().skip(1))
|
||||
.for_each(|(pos, segment)| {
|
||||
*positions.get_mut(*segment).unwrap() = *pos;
|
||||
})
|
||||
});
|
||||
last_tail_position.0 = Some(*segment_positions.last().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
fn snake_eating(
|
||||
commands: &mut Commands,
|
||||
snake_timer: ResMut<SnakeMoveTimer>,
|
||||
mut growth_events: ResMut<Events<GrowthEvent>>,
|
||||
food_positions: Query<(Entity, &Position), With<Food>>,
|
||||
head_positions: Query<&Position, With<SnakeHead>>,
|
||||
) {
|
||||
if !snake_timer.0.finished() {
|
||||
return;
|
||||
}
|
||||
for head_pos in head_positions.iter() {
|
||||
for (ent, food_pos) in food_positions.iter() {
|
||||
if food_pos == head_pos {
|
||||
commands.despawn(ent);
|
||||
growth_events.send(GrowthEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn snake_growth(
|
||||
commands: &mut Commands,
|
||||
last_tail_position: Res<LastTailPosition>,
|
||||
growth_events: Res<Events<GrowthEvent>>,
|
||||
mut segments: ResMut<SnakeSegments>,
|
||||
mut growth_reader: Local<EventReader<GrowthEvent>>,
|
||||
materials: Res<Materials>,
|
||||
) {
|
||||
if growth_reader.iter(&growth_events).next().is_some() {
|
||||
segments.0.push(spawn_segment(
|
||||
commands,
|
||||
&materials.segment_material,
|
||||
last_tail_position.0.unwrap(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@ -238,6 +282,8 @@ fn main() {
|
||||
})
|
||||
.add_resource(SnakeMoveTimer(Timer::new(Duration::from_millis(150), true)))
|
||||
.add_resource(SnakeSegments::default())
|
||||
.add_resource(LastTailPosition::default())
|
||||
.add_event::<GrowthEvent>()
|
||||
.add_startup_system(setup.system())
|
||||
.add_startup_stage("game_setup", SystemStage::single(spawn_snake.system()))
|
||||
.add_system(snake_movement.system())
|
||||
@ -245,6 +291,8 @@ fn main() {
|
||||
.add_system(size_scaling.system())
|
||||
.add_system(food_spawner.system())
|
||||
.add_system(snake_timer.system())
|
||||
.add_system(snake_eating.system())
|
||||
.add_system(snake_growth.system())
|
||||
.add_plugins(DefaultPlugins)
|
||||
.run();
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user