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: f32 = 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 .add_schedule(FixedUpdate)
60 .at(percent(35), percent(50)),
61 )
62 .insert_resource(Score(0))
63 .insert_resource(ClearColor(BACKGROUND_COLOR))
64 .add_systems(Startup, setup)
65 .add_systems(
68 FixedUpdate,
69 (apply_velocity, move_paddle, check_for_collisions)
70 .chain(),
72 )
73 .add_systems(Update, update_scoreboard)
74 .add_observer(play_collision_sound)
75 .run();
76}
77
78#[derive(Component)]
79struct Paddle;
80
81#[derive(Component)]
82struct Ball;
83
84#[derive(Component, Deref, DerefMut)]
85struct Velocity(Vec2);
86
87#[derive(Event)]
88struct BallCollided;
89
90#[derive(Component)]
91struct Brick;
92
93#[derive(Resource, Deref)]
94struct CollisionSound(Handle<AudioSource>);
95
96#[derive(Component, Default)]
98struct Collider;
99
100#[derive(Component)]
102#[require(Sprite, Transform, Collider)]
103struct Wall;
104
105enum WallLocation {
107 Left,
108 Right,
109 Bottom,
110 Top,
111}
112
113impl WallLocation {
114 fn position(&self) -> Vec2 {
116 match self {
117 WallLocation::Left => Vec2::new(LEFT_WALL, 0.),
118 WallLocation::Right => Vec2::new(RIGHT_WALL, 0.),
119 WallLocation::Bottom => Vec2::new(0., BOTTOM_WALL),
120 WallLocation::Top => Vec2::new(0., TOP_WALL),
121 }
122 }
123
124 fn size(&self) -> Vec2 {
126 let arena_height = TOP_WALL - BOTTOM_WALL;
127 let arena_width = RIGHT_WALL - LEFT_WALL;
128 assert!(arena_height > 0.0);
130 assert!(arena_width > 0.0);
131
132 match self {
133 WallLocation::Left | WallLocation::Right => {
134 Vec2::new(WALL_THICKNESS, arena_height + WALL_THICKNESS)
135 }
136 WallLocation::Bottom | WallLocation::Top => {
137 Vec2::new(arena_width + WALL_THICKNESS, WALL_THICKNESS)
138 }
139 }
140 }
141}
142
143impl Wall {
144 fn new(location: WallLocation) -> (Wall, Sprite, Transform) {
148 (
149 Wall,
150 Sprite::from_color(WALL_COLOR, Vec2::ONE),
151 Transform {
152 translation: location.position().extend(0.0),
155 scale: location.size().extend(1.0),
159 ..default()
160 },
161 )
162 }
163}
164
165#[derive(Resource, Deref, DerefMut)]
167struct Score(usize);
168
169#[derive(Component)]
170struct ScoreboardUi;
171
172fn setup(
174 mut commands: Commands,
175 mut meshes: ResMut<Assets<Mesh>>,
176 mut materials: ResMut<Assets<ColorMaterial>>,
177 asset_server: Res<AssetServer>,
178) {
179 commands.spawn(Camera2d);
181
182 let ball_collision_sound = asset_server.load("sounds/breakout_collision.ogg");
184 commands.insert_resource(CollisionSound(ball_collision_sound));
185
186 let paddle_y = BOTTOM_WALL + GAP_BETWEEN_PADDLE_AND_FLOOR;
188
189 commands.spawn((
190 Sprite::from_color(PADDLE_COLOR, Vec2::ONE),
191 Transform {
192 translation: Vec3::new(0.0, paddle_y, 0.0),
193 scale: PADDLE_SIZE.extend(1.0),
194 ..default()
195 },
196 Paddle,
197 Collider,
198 ));
199
200 commands.spawn((
202 Mesh2d(meshes.add(Circle::default())),
203 MeshMaterial2d(materials.add(BALL_COLOR)),
204 Transform::from_translation(BALL_STARTING_POSITION)
205 .with_scale(Vec2::splat(BALL_DIAMETER).extend(1.)),
206 Ball,
207 Velocity(INITIAL_BALL_DIRECTION.normalize() * BALL_SPEED),
208 ));
209
210 commands.spawn((
212 Text::new("Score: "),
213 TextFont {
214 font_size: SCOREBOARD_FONT_SIZE,
215 ..default()
216 },
217 TextColor(TEXT_COLOR),
218 ScoreboardUi,
219 Node {
220 position_type: PositionType::Absolute,
221 top: SCOREBOARD_TEXT_PADDING,
222 left: SCOREBOARD_TEXT_PADDING,
223 ..default()
224 },
225 children![(
226 TextSpan::default(),
227 TextFont {
228 font_size: SCOREBOARD_FONT_SIZE,
229 ..default()
230 },
231 TextColor(SCORE_COLOR),
232 )],
233 ));
234
235 commands.spawn(Wall::new(WallLocation::Left));
237 commands.spawn(Wall::new(WallLocation::Right));
238 commands.spawn(Wall::new(WallLocation::Bottom));
239 commands.spawn(Wall::new(WallLocation::Top));
240
241 let total_width_of_bricks = (RIGHT_WALL - LEFT_WALL) - 2. * GAP_BETWEEN_BRICKS_AND_SIDES;
243 let bottom_edge_of_bricks = paddle_y + GAP_BETWEEN_PADDLE_AND_BRICKS;
244 let total_height_of_bricks = TOP_WALL - bottom_edge_of_bricks - GAP_BETWEEN_BRICKS_AND_CEILING;
245
246 assert!(total_width_of_bricks > 0.0);
247 assert!(total_height_of_bricks > 0.0);
248
249 let n_columns = (total_width_of_bricks / (BRICK_SIZE.x + GAP_BETWEEN_BRICKS)).floor() as usize;
251 let n_rows = (total_height_of_bricks / (BRICK_SIZE.y + GAP_BETWEEN_BRICKS)).floor() as usize;
252 let n_vertical_gaps = n_columns - 1;
253
254 let center_of_bricks = (LEFT_WALL + RIGHT_WALL) / 2.0;
257 let left_edge_of_bricks = center_of_bricks
258 - (n_columns as f32 / 2.0 * BRICK_SIZE.x)
260 - n_vertical_gaps as f32 / 2.0 * GAP_BETWEEN_BRICKS;
262
263 let offset_x = left_edge_of_bricks + BRICK_SIZE.x / 2.;
266 let offset_y = bottom_edge_of_bricks + BRICK_SIZE.y / 2.;
267
268 for row in 0..n_rows {
269 for column in 0..n_columns {
270 let brick_position = Vec2::new(
271 offset_x + column as f32 * (BRICK_SIZE.x + GAP_BETWEEN_BRICKS),
272 offset_y + row as f32 * (BRICK_SIZE.y + GAP_BETWEEN_BRICKS),
273 );
274
275 commands.spawn((
277 Sprite {
278 color: BRICK_COLOR,
279 ..default()
280 },
281 Transform {
282 translation: brick_position.extend(0.0),
283 scale: Vec3::new(BRICK_SIZE.x, BRICK_SIZE.y, 1.0),
284 ..default()
285 },
286 Brick,
287 Collider,
288 ));
289 }
290 }
291}
292
293fn move_paddle(
294 keyboard_input: Res<ButtonInput<KeyCode>>,
295 mut paddle_transform: Single<&mut Transform, With<Paddle>>,
296 time: Res<Time>,
297) {
298 let mut direction = 0.0;
299
300 if keyboard_input.pressed(KeyCode::ArrowLeft) {
301 direction -= 1.0;
302 }
303
304 if keyboard_input.pressed(KeyCode::ArrowRight) {
305 direction += 1.0;
306 }
307
308 let new_paddle_position =
310 paddle_transform.translation.x + direction * PADDLE_SPEED * time.delta_secs();
311
312 let left_bound = LEFT_WALL + WALL_THICKNESS / 2.0 + PADDLE_SIZE.x / 2.0 + PADDLE_PADDING;
315 let right_bound = RIGHT_WALL - WALL_THICKNESS / 2.0 - PADDLE_SIZE.x / 2.0 - PADDLE_PADDING;
316
317 paddle_transform.translation.x = new_paddle_position.clamp(left_bound, right_bound);
318}
319
320fn apply_velocity(mut query: Query<(&mut Transform, &Velocity)>, time: Res<Time>) {
321 for (mut transform, velocity) in &mut query {
322 transform.translation.x += velocity.x * time.delta_secs();
323 transform.translation.y += velocity.y * time.delta_secs();
324 }
325}
326
327fn update_scoreboard(
328 score: Res<Score>,
329 score_root: Single<Entity, (With<ScoreboardUi>, With<Text>)>,
330 mut writer: TextUiWriter,
331) {
332 *writer.text(*score_root, 1) = score.to_string();
333}
334
335fn check_for_collisions(
336 mut commands: Commands,
337 mut score: ResMut<Score>,
338 ball_query: Single<(&mut Velocity, &Transform), With<Ball>>,
339 collider_query: Query<(Entity, &Transform, Option<&Brick>), With<Collider>>,
340) {
341 let (mut ball_velocity, ball_transform) = ball_query.into_inner();
342
343 for (collider_entity, collider_transform, maybe_brick) in &collider_query {
344 let collision = ball_collision(
345 BoundingCircle::new(ball_transform.translation.truncate(), BALL_DIAMETER / 2.),
346 Aabb2d::new(
347 collider_transform.translation.truncate(),
348 collider_transform.scale.truncate() / 2.,
349 ),
350 );
351
352 if let Some(collision) = collision {
353 commands.trigger(BallCollided);
355
356 if maybe_brick.is_some() {
358 commands.entity(collider_entity).despawn();
359 **score += 1;
360 }
361
362 let mut reflect_x = false;
364 let mut reflect_y = false;
365
366 match collision {
369 Collision::Left => reflect_x = ball_velocity.x > 0.0,
370 Collision::Right => reflect_x = ball_velocity.x < 0.0,
371 Collision::Top => reflect_y = ball_velocity.y < 0.0,
372 Collision::Bottom => reflect_y = ball_velocity.y > 0.0,
373 }
374
375 if reflect_x {
377 ball_velocity.x = -ball_velocity.x;
378 }
379
380 if reflect_y {
382 ball_velocity.y = -ball_velocity.y;
383 }
384 }
385 }
386}
387
388fn play_collision_sound(
389 _collided: On<BallCollided>,
390 mut commands: Commands,
391 sound: Res<CollisionSound>,
392) {
393 commands.spawn((AudioPlayer(sound.clone()), PlaybackSettings::DESPAWN));
394}
395
396#[derive(Debug, PartialEq, Eq, Copy, Clone)]
397enum Collision {
398 Left,
399 Right,
400 Top,
401 Bottom,
402}
403
404fn ball_collision(ball: BoundingCircle, bounding_box: Aabb2d) -> Option<Collision> {
407 if !ball.intersects(&bounding_box) {
408 return None;
409 }
410
411 let closest = bounding_box.closest_point(ball.center());
412 let offset = ball.center() - closest;
413 let side = if offset.x.abs() > offset.y.abs() {
414 if offset.x < 0. {
415 Collision::Left
416 } else {
417 Collision::Right
418 }
419 } else if offset.y > 0. {
420 Collision::Top
421 } else {
422 Collision::Bottom
423 };
424
425 Some(side)
426}