@@ -4,6 +4,7 @@ use rand::prelude::random;
4
4
5
5
const SNAKE_HEAD_COLOR : Color = Color :: rgb ( 0.7 , 0.7 , 0.7 ) ;
6
6
const FOOD_COLOR : Color = Color :: rgb ( 1.0 , 0.0 , 1.0 ) ;
7
+ const SNAKE_SEGMENT_COLOR : Color = Color :: rgb ( 0.3 , 0.3 , 0.3 ) ;
7
8
8
9
const ARENA_HEIGHT : u32 = 10 ;
9
10
const ARENA_WIDTH : u32 = 10 ;
@@ -33,6 +34,12 @@ struct SnakeHead {
33
34
direction : Direction ,
34
35
}
35
36
37
+ #[ derive( Component ) ]
38
+ struct SnakeSegment ;
39
+
40
+ #[ derive( Default , Deref , DerefMut ) ]
41
+ struct SnakeSegments ( Vec < Entity > ) ;
42
+
36
43
#[ derive( Component ) ]
37
44
struct Food ;
38
45
@@ -59,24 +66,40 @@ fn setup_camera(mut commands: Commands) {
59
66
commands. spawn_bundle ( OrthographicCameraBundle :: new_2d ( ) ) ;
60
67
}
61
68
62
- fn spawn_snake ( mut commands : Commands ) {
69
+ fn spawn_snake ( mut commands : Commands , mut segments : ResMut < SnakeSegments > ) {
70
+ * segments = SnakeSegments ( vec ! [
71
+ commands
72
+ . spawn_bundle( SpriteBundle {
73
+ sprite: Sprite {
74
+ color: SNAKE_HEAD_COLOR ,
75
+ ..default ( )
76
+ } ,
77
+ ..default ( )
78
+ } )
79
+ . insert( SnakeHead {
80
+ direction: Direction :: Up ,
81
+ } )
82
+ . insert( SnakeSegment )
83
+ . insert( Position { x: 3 , y: 3 } )
84
+ . insert( Size :: square( 0.8 ) )
85
+ . id( ) ,
86
+ spawn_segment( commands, Position { x: 3 , y: 2 } ) ,
87
+ ] ) ;
88
+ }
89
+
90
+ fn spawn_segment ( mut commands : Commands , position : Position ) -> Entity {
63
91
commands
64
92
. spawn_bundle ( SpriteBundle {
65
93
sprite : Sprite {
66
- color : SNAKE_HEAD_COLOR ,
67
- ..default ( )
68
- } ,
69
- transform : Transform {
70
- scale : Vec3 :: new ( 10.0 , 10.0 , 10.0 ) ,
94
+ color : SNAKE_SEGMENT_COLOR ,
71
95
..default ( )
72
96
} ,
73
97
..default ( )
74
98
} )
75
- . insert ( SnakeHead {
76
- direction : Direction :: Up ,
77
- } )
78
- . insert ( Position { x : 3 , y : 3 } )
79
- . insert ( Size :: square ( 0.8 ) ) ;
99
+ . insert ( SnakeSegment )
100
+ . insert ( position)
101
+ . insert ( Size :: square ( 0.65 ) )
102
+ . id ( )
80
103
}
81
104
82
105
fn snake_movement_input ( keyboard_input : Res < Input < KeyCode > > , mut heads : Query < & mut SnakeHead > ) {
@@ -177,6 +200,7 @@ fn main() {
177
200
. with_run_criteria ( FixedTimestep :: step ( 0.150 ) )
178
201
. with_system ( snake_movement) ,
179
202
)
203
+ . insert_resource ( SnakeSegments :: default ( ) )
180
204
. add_system_set (
181
205
SystemSet :: new ( )
182
206
. with_run_criteria ( FixedTimestep :: step ( 1.0 ) )
0 commit comments