@@ -102,6 +102,40 @@ fn spawn_segment(mut commands: Commands, position: Position) -> Entity {
102102 . id ( )
103103}
104104
105+ fn snake_movement (
106+ segments : ResMut < SnakeSegments > ,
107+ mut heads : Query < ( Entity , & SnakeHead ) > ,
108+ mut positions : Query < & mut Position > ,
109+ ) {
110+ if let Some ( ( head_entity, head) ) = heads. iter_mut ( ) . next ( ) {
111+ let segment_positions = segments
112+ . iter ( )
113+ . map ( |e| * positions. get_mut ( * e) . unwrap ( ) )
114+ . collect :: < Vec < Position > > ( ) ;
115+ let mut head_pos = positions. get_mut ( head_entity) . unwrap ( ) ;
116+ match & head. direction {
117+ Direction :: Left => {
118+ head_pos. x -= 1 ;
119+ }
120+ Direction :: Right => {
121+ head_pos. x += 1 ;
122+ }
123+ Direction :: Up => {
124+ head_pos. y += 1 ;
125+ }
126+ Direction :: Down => {
127+ head_pos. y -= 1 ;
128+ }
129+ } ;
130+ segment_positions
131+ . iter ( )
132+ . zip ( segments. iter ( ) . skip ( 1 ) )
133+ . for_each ( |( pos, segment) | {
134+ * positions. get_mut ( * segment) . unwrap ( ) = * pos;
135+ } ) ;
136+ }
137+ }
138+
105139fn snake_movement_input ( keyboard_input : Res < Input < KeyCode > > , mut heads : Query < & mut SnakeHead > ) {
106140 if let Some ( mut head) = heads. iter_mut ( ) . next ( ) {
107141 let dir: Direction = if keyboard_input. pressed ( KeyCode :: Left ) {
@@ -121,25 +155,6 @@ fn snake_movement_input(keyboard_input: Res<Input<KeyCode>>, mut heads: Query<&m
121155 }
122156}
123157
124- fn snake_movement ( mut heads : Query < ( & mut Position , & SnakeHead ) > ) {
125- if let Some ( ( mut head_pos, head) ) = heads. iter_mut ( ) . next ( ) {
126- match & head. direction {
127- Direction :: Left => {
128- head_pos. x -= 1 ;
129- }
130- Direction :: Right => {
131- head_pos. x += 1 ;
132- }
133- Direction :: Up => {
134- head_pos. y += 1 ;
135- }
136- Direction :: Down => {
137- head_pos. y -= 1 ;
138- }
139- } ;
140- }
141- }
142-
143158fn size_scaling ( windows : Res < Windows > , mut q : Query < ( & Size , & mut Transform ) > ) {
144159 let window = windows. get_primary ( ) . unwrap ( ) ;
145160 for ( sprite_size, mut transform) in q. iter_mut ( ) {
0 commit comments