@@ -2,6 +2,29 @@ use bevy::prelude::*;
22
33const SNAKE_HEAD_COLOR : Color = Color :: rgb ( 0.7 , 0.7 , 0.7 ) ;
44
5+ const ARENA_HEIGHT : u32 = 10 ;
6+ const ARENA_WIDTH : u32 = 10 ;
7+
8+ #[ derive( Component , Clone , Copy , PartialEq , Eq ) ]
9+ struct Position {
10+ x : i32 ,
11+ y : i32 ,
12+ }
13+
14+ #[ derive( Component ) ]
15+ struct Size {
16+ width : f32 ,
17+ height : f32 ,
18+ }
19+ impl Size {
20+ pub fn square ( x : f32 ) -> Self {
21+ Self {
22+ width : x,
23+ height : x,
24+ }
25+ }
26+ }
27+
528#[ derive( Component ) ]
629struct SnakeHead ;
730
@@ -22,7 +45,9 @@ fn spawn_snake(mut commands: Commands) {
2245 } ,
2346 ..default ( )
2447 } )
25- . insert ( SnakeHead ) ;
48+ . insert ( SnakeHead )
49+ . insert ( Position { x : 3 , y : 3 } )
50+ . insert ( Size :: square ( 0.8 ) ) ;
2651}
2752
2853fn snake_movement (
@@ -45,11 +70,43 @@ fn snake_movement(
4570 }
4671}
4772
73+ fn size_scaling ( windows : Res < Windows > , mut q : Query < ( & Size , & mut Transform ) > ) {
74+ let window = windows. get_primary ( ) . unwrap ( ) ;
75+ for ( sprite_size, mut transform) in q. iter_mut ( ) {
76+ transform. scale = Vec3 :: new (
77+ sprite_size. width / ARENA_WIDTH as f32 * window. width ( ) as f32 ,
78+ sprite_size. height / ARENA_HEIGHT as f32 * window. height ( ) as f32 ,
79+ 1.0 ,
80+ ) ;
81+ }
82+ }
83+
84+ fn position_translation ( windows : Res < Windows > , mut q : Query < ( & Position , & mut Transform ) > ) {
85+ fn convert ( pos : f32 , bound_window : f32 , bound_game : f32 ) -> f32 {
86+ let tile_size = bound_window / bound_game;
87+ pos / bound_game * bound_window - ( bound_window / 2. ) + ( tile_size / 2. )
88+ }
89+ let window = windows. get_primary ( ) . unwrap ( ) ;
90+ for ( pos, mut transform) in q. iter_mut ( ) {
91+ transform. translation = Vec3 :: new (
92+ convert ( pos. x as f32 , window. width ( ) as f32 , ARENA_WIDTH as f32 ) ,
93+ convert ( pos. y as f32 , window. height ( ) as f32 , ARENA_HEIGHT as f32 ) ,
94+ 0.0 ,
95+ ) ;
96+ }
97+ }
98+
4899fn main ( ) {
49100 App :: new ( )
50101 . add_startup_system ( setup_camera)
51102 . add_startup_system ( spawn_snake)
52103 . add_system ( snake_movement)
104+ . add_system_set_to_stage (
105+ CoreStage :: PostUpdate ,
106+ SystemSet :: new ( )
107+ . with_system ( position_translation)
108+ . with_system ( size_scaling) ,
109+ )
53110 . add_plugins ( DefaultPlugins )
54111 . run ( ) ;
55112}
0 commit comments