1use bevy::{
6 math::bounding::{Aabb2d, BoundingCircle, BoundingVolume, IntersectsVolume},
7 prelude::*,
8};
9
10mod stepping;
11
12const PADDLE_SIZE: Vec2 = Vec2::new(120.0, 20.0);
15const GAP_BETWEEN_PADDLE_AND_FLOOR: f32 = 60.0;
16const PADDLE_SPEED: f32 = 500.0;
17const PADDLE_PADDING: f32 = 10.0;
19
20const BALL_STARTING_POSITION: Vec3 = Vec3::new(0.0, -50.0, 1.0);
22const BALL_DIAMETER: f32 = 30.;
23const BALL_SPEED: f32 = 400.0;
24const INITIAL_BALL_DIRECTION: Vec2 = Vec2::new(0.5, -0.5);
25
26const WALL_THICKNESS: f32 = 10.0;
27const LEFT_WALL: f32 = -450.;
29const RIGHT_WALL: f32 = 450.;
30const BOTTOM_WALL: f32 = -300.;
32const TOP_WALL: f32 = 300.;
33
34const BRICK_SIZE: Vec2 = Vec2::new(100., 30.);
35const GAP_BETWEEN_PADDLE_AND_BRICKS: f32 = 270.0;
37const GAP_BETWEEN_BRICKS: f32 = 5.0;
38const GAP_BETWEEN_BRICKS_AND_CEILING: f32 = 20.0;
40const GAP_BETWEEN_BRICKS_AND_SIDES: f32 = 20.0;
41
42const SCOREBOARD_FONT_SIZE: FontSize = FontSize::Px(33.0);
43const SCOREBOARD_TEXT_PADDING: Val = Val::Px(5.0);
44
45const BACKGROUND_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
46const PADDLE_COLOR: Color = Color::srgb(0.3, 0.3, 0.7);
47const BALL_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
48const BRICK_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
49const WALL_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
50const TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
51const SCORE_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
52
53fn main() {
54 App::new()
55 .add_plugins(DefaultPlugins)
56 .add_plugins(
57 stepping::SteppingPlugin::default()
58 .add_schedule(Update)
59 .at(percent(35), percent(50)),
60 )
61 .insert_resource(Score(0))
62 .insert_resource(ClearColor(BACKGROUND_COLOR))
63 .add_systems(Startup, setup)
64 .add_systems(
67 Update,
68 (apply_velocity, move_paddle, check_for_collisions)
69 .chain(),
71 )
72 .add_systems(Update, update_scoreboard)
73 .add_observer(play_collision_sound)
74 .run();
75}
76
77#[derive(Component)]
78struct Paddle;
79
80#[derive(Component)]
81struct Ball;
82
83#[derive(Component, Deref, DerefMut)]
84struct Velocity(Vec2);
85
86#[derive(Event)]
87struct BallCollided;
88
89#[derive(Component)]
90struct Brick;
91
92#[derive(Resource, Deref)]
93struct CollisionSound(Handle<AudioSource>);
94
95#[derive(Component, Default)]
97struct Collider;
98
99#[derive(Component)]
101#[require(Sprite, Transform, Collider)]
102struct Wall;
103
104enum WallLocation {
106 Left,
107 Right,
108 Bottom,
109 Top,
110}
111
112impl WallLocation {
113 fn position(&self) -> Vec2 {
115 match self {
116 WallLocation::Left => Vec2::new(LEFT_WALL, 0.),
117 WallLocation::Right => Vec2::new(RIGHT_WALL, 0.),
118 WallLocation::Bottom => Vec2::new(0., BOTTOM_WALL),
119 WallLocation::Top => Vec2::new(0., TOP_WALL),
120 }
121 }
122
123 fn size(&self) -> Vec2 {
125 let arena_height = TOP_WALL - BOTTOM_WALL;
126 let arena_width = RIGHT_WALL - LEFT_WALL;
127 assert!(arena_height > 0.0);
129 assert!(arena_width > 0.0);
130
131 match self {
132 WallLocation::Left | WallLocation::Right => {
133 Vec2::new(WALL_THICKNESS, arena_height + WALL_THICKNESS)
134 }
135 WallLocation::Bottom | WallLocation::Top => {
136 Vec2::new(arena_width + WALL_THICKNESS, WALL_THICKNESS)
137 }
138 }
139 }
140}
141
142impl Wall {
143 fn new(location: WallLocation) -> (Wall, Sprite, Transform) {
147 (
148 Wall,
149 Sprite::from_color(WALL_COLOR, Vec2::ONE),
150 Transform {
151 translation: location.position().extend(0.0),
154 scale: location.size().extend(1.0),
158 ..default()
159 },
160 )
161 }
162}
163
164#[derive(Resource, Deref, DerefMut)]
166struct Score(usize);
167
168#[derive(Component)]
169struct ScoreboardUi;
170
171fn setup(
173 mut commands: Commands,
174 mut meshes: ResMut<Assets<Mesh>>,
175 mut materials: ResMut<Assets<ColorMaterial>>,
176 asset_server: Res<AssetServer>,
177) {
178 commands.spawn(Camera2d);
180
181 let ball_collision_sound = asset_server.load("sounds/breakout_collision.ogg");
183 commands.insert_resource(CollisionSound(ball_collision_sound));
184
185 let paddle_y = BOTTOM_WALL + GAP_BETWEEN_PADDLE_AND_FLOOR;
187
188 commands.spawn((
189 Sprite::from_color(PADDLE_COLOR, Vec2::ONE),
190 Transform {
191 translation: Vec3::new(0.0, paddle_y, 0.0),
192 scale: PADDLE_SIZE.extend(1.0),
193 ..default()
194 },
195 Paddle,
196 Collider,
197 ));
198
199 commands.spawn((
201 Mesh2d(meshes.add(Circle::default())),
202 MeshMaterial2d(materials.add(BALL_COLOR)),
203 Transform::from_translation(BALL_STARTING_POSITION)
204 .with_scale(Vec2::splat(BALL_DIAMETER).extend(1.)),
205 Ball,
206 Velocity(INITIAL_BALL_DIRECTION.normalize() * BALL_SPEED),
207 ));
208
209 commands.spawn((
211 Text::new("Score: "),
212 TextFont {
213 font_size: SCOREBOARD_FONT_SIZE,
214 ..default()
215 },
216 TextColor(TEXT_COLOR),
217 ScoreboardUi,
218 Node {
219 position_type: PositionType::Absolute,
220 top: SCOREBOARD_TEXT_PADDING,
221 left: SCOREBOARD_TEXT_PADDING,
222 ..default()
223 },
224 children![(
225 TextSpan::default(),
226 TextFont {
227 font_size: SCOREBOARD_FONT_SIZE,
228 ..default()
229 },
230 TextColor(SCORE_COLOR),
231 )],
232 ));
233
234 commands.spawn(Wall::new(WallLocation::Left));
236 commands.spawn(Wall::new(WallLocation::Right));
237 commands.spawn(Wall::new(WallLocation::Bottom));
238 commands.spawn(Wall::new(WallLocation::Top));
239
240 let total_width_of_bricks = (RIGHT_WALL - LEFT_WALL) - 2. * GAP_BETWEEN_BRICKS_AND_SIDES;
242 let bottom_edge_of_bricks = paddle_y + GAP_BETWEEN_PADDLE_AND_BRICKS;
243 let total_height_of_bricks = TOP_WALL - bottom_edge_of_bricks - GAP_BETWEEN_BRICKS_AND_CEILING;
244
245 assert!(total_width_of_bricks > 0.0);
246 assert!(total_height_of_bricks > 0.0);
247
248 let n_columns = (total_width_of_bricks / (BRICK_SIZE.x + GAP_BETWEEN_BRICKS)).floor() as usize;
250 let n_rows = (total_height_of_bricks / (BRICK_SIZE.y + GAP_BETWEEN_BRICKS)).floor() as usize;
251 let n_vertical_gaps = n_columns - 1;
252
253 let center_of_bricks = (LEFT_WALL + RIGHT_WALL) / 2.0;
256 let left_edge_of_bricks = center_of_bricks
257 - (n_columns as f32 / 2.0 * BRICK_SIZE.x)
259 - n_vertical_gaps as f32 / 2.0 * GAP_BETWEEN_BRICKS;
261
262 let offset_x = left_edge_of_bricks + BRICK_SIZE.x / 2.;
265 let offset_y = bottom_edge_of_bricks + BRICK_SIZE.y / 2.;
266
267 for row in 0..n_rows {
268 for column in 0..n_columns {
269 let brick_position = Vec2::new(
270 offset_x + column as f32 * (BRICK_SIZE.x + GAP_BETWEEN_BRICKS),
271 offset_y + row as f32 * (BRICK_SIZE.y + GAP_BETWEEN_BRICKS),
272 );
273
274 commands.spawn((
276 Sprite {
277 color: BRICK_COLOR,
278 ..default()
279 },
280 Transform {
281 translation: brick_position.extend(0.0),
282 scale: Vec3::new(BRICK_SIZE.x, BRICK_SIZE.y, 1.0),
283 ..default()
284 },
285 Brick,
286 Collider,
287 ));
288 }
289 }
290}
291
292fn move_paddle(
293 keyboard_input: Res<ButtonInput<KeyCode>>,
294 mut paddle_transform: Single<&mut Transform, With<Paddle>>,
295 time: Res<Time>,
296) {
297 let mut direction = 0.0;
298
299 if keyboard_input.pressed(KeyCode::ArrowLeft) {
300 direction -= 1.0;
301 }
302
303 if keyboard_input.pressed(KeyCode::ArrowRight) {
304 direction += 1.0;
305 }
306
307 let new_paddle_position =
309 paddle_transform.translation.x + direction * PADDLE_SPEED * time.delta_secs();
310
311 let left_bound = LEFT_WALL + WALL_THICKNESS / 2.0 + PADDLE_SIZE.x / 2.0 + PADDLE_PADDING;
314 let right_bound = RIGHT_WALL - WALL_THICKNESS / 2.0 - PADDLE_SIZE.x / 2.0 - PADDLE_PADDING;
315
316 paddle_transform.translation.x = new_paddle_position.clamp(left_bound, right_bound);
317}
318
319fn apply_velocity(mut query: Query<(&mut Transform, &Velocity)>, time: Res<Time>) {
320 for (mut transform, velocity) in &mut query {
321 transform.translation.x += velocity.x * time.delta_secs();
322 transform.translation.y += velocity.y * time.delta_secs();
323 }
324}
325
326fn update_scoreboard(
327 score: Res<Score>,
328 score_root: Single<Entity, (With<ScoreboardUi>, With<Text>)>,
329 mut writer: TextUiWriter,
330) {
331 *writer.text(*score_root, 1) = score.to_string();
332}
333
334fn check_for_collisions(
335 mut commands: Commands,
336 mut score: ResMut<Score>,
337 ball_query: Single<(&mut Velocity, &Transform), With<Ball>>,
338 collider_query: Query<(Entity, &Transform, Option<&Brick>), With<Collider>>,
339) {
340 let (mut ball_velocity, ball_transform) = ball_query.into_inner();
341
342 for (collider_entity, collider_transform, maybe_brick) in &collider_query {
343 let collision = ball_collision(
344 BoundingCircle::new(ball_transform.translation.truncate(), BALL_DIAMETER / 2.),
345 Aabb2d::new(
346 collider_transform.translation.truncate(),
347 collider_transform.scale.truncate() / 2.,
348 ),
349 );
350
351 if let Some(collision) = collision {
352 commands.trigger(BallCollided);
354
355 if maybe_brick.is_some() {
357 commands.entity(collider_entity).despawn();
358 **score += 1;
359 }
360
361 let mut reflect_x = false;
363 let mut reflect_y = false;
364
365 match collision {
368 Collision::Left => reflect_x = ball_velocity.x > 0.0,
369 Collision::Right => reflect_x = ball_velocity.x < 0.0,
370 Collision::Top => reflect_y = ball_velocity.y < 0.0,
371 Collision::Bottom => reflect_y = ball_velocity.y > 0.0,
372 }
373
374 if reflect_x {
376 ball_velocity.x = -ball_velocity.x;
377 }
378
379 if reflect_y {
381 ball_velocity.y = -ball_velocity.y;
382 }
383 }
384 }
385}
386
387fn play_collision_sound(
388 _collided: On<BallCollided>,
389 mut commands: Commands,
390 sound: Res<CollisionSound>,
391) {
392 commands.spawn((AudioPlayer(sound.clone()), PlaybackSettings::DESPAWN));
393}
394
395#[derive(Debug, PartialEq, Eq, Copy, Clone)]
396enum Collision {
397 Left,
398 Right,
399 Top,
400 Bottom,
401}
402
403fn ball_collision(ball: BoundingCircle, bounding_box: Aabb2d) -> Option<Collision> {
406 if !ball.intersects(&bounding_box) {
407 return None;
408 }
409
410 let closest = bounding_box.closest_point(ball.center());
411 let offset = ball.center() - closest;
412 let side = if offset.x.abs() > offset.y.abs() {
413 if offset.x < 0. {
414 Collision::Left
415 } else {
416 Collision::Right
417 }
418 } else if offset.y > 0. {
419 Collision::Top
420 } else {
421 Collision::Bottom
422 };
423
424 Some(side)
425}