Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/showcase/breakout.rs
30632 views
1
//! A simplified implementation of the classic game "Breakout".
2
//!
3
//! Demonstrates Bevy's stepping capabilities if compiled with the `bevy_debug_stepping` feature.
4
5
use bevy::{
6
math::bounding::{Aabb2d, BoundingCircle, BoundingVolume, IntersectsVolume},
7
prelude::*,
8
};
9
10
mod stepping;
11
12
// These constants are defined in `Transform` units.
13
// Using the default 2D camera they correspond 1:1 with screen pixels.
14
const PADDLE_SIZE: Vec2 = Vec2::new(120.0, 20.0);
15
const GAP_BETWEEN_PADDLE_AND_FLOOR: f32 = 60.0;
16
const PADDLE_SPEED: f32 = 500.0;
17
// How close can the paddle get to the wall
18
const PADDLE_PADDING: f32 = 10.0;
19
20
// We set the z-value of the ball to 1 so it renders on top in the case of overlapping sprites.
21
const BALL_STARTING_POSITION: Vec3 = Vec3::new(0.0, -50.0, 1.0);
22
const BALL_DIAMETER: f32 = 30.;
23
const BALL_SPEED: f32 = 400.0;
24
const INITIAL_BALL_DIRECTION: Vec2 = Vec2::new(0.5, -0.5);
25
26
const WALL_THICKNESS: f32 = 10.0;
27
// x coordinates
28
const LEFT_WALL: f32 = -450.;
29
const RIGHT_WALL: f32 = 450.;
30
// y coordinates
31
const BOTTOM_WALL: f32 = -300.;
32
const TOP_WALL: f32 = 300.;
33
34
const BRICK_SIZE: Vec2 = Vec2::new(100., 30.);
35
// These values are exact
36
const GAP_BETWEEN_PADDLE_AND_BRICKS: f32 = 270.0;
37
const GAP_BETWEEN_BRICKS: f32 = 5.0;
38
// These values are lower bounds, as the number of bricks is computed
39
const GAP_BETWEEN_BRICKS_AND_CEILING: f32 = 20.0;
40
const GAP_BETWEEN_BRICKS_AND_SIDES: f32 = 20.0;
41
42
const SCOREBOARD_FONT_SIZE: FontSize = FontSize::Px(33.0);
43
const SCOREBOARD_TEXT_PADDING: Val = Val::Px(5.0);
44
45
const BACKGROUND_COLOR: Color = Color::srgb(0.9, 0.9, 0.9);
46
const PADDLE_COLOR: Color = Color::srgb(0.3, 0.3, 0.7);
47
const BALL_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
48
const BRICK_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
49
const WALL_COLOR: Color = Color::srgb(0.8, 0.8, 0.8);
50
const TEXT_COLOR: Color = Color::srgb(0.5, 0.5, 1.0);
51
const SCORE_COLOR: Color = Color::srgb(1.0, 0.5, 0.5);
52
53
fn 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 our simulation systems to the update schedule
65
// which is called once per frame.
66
.add_systems(
67
Update,
68
(apply_velocity, move_paddle, check_for_collisions)
69
// `chain`ing systems together runs them in order
70
.chain(),
71
)
72
.add_systems(Update, update_scoreboard)
73
.add_observer(play_collision_sound)
74
.run();
75
}
76
77
#[derive(Component)]
78
struct Paddle;
79
80
#[derive(Component)]
81
struct Ball;
82
83
#[derive(Component, Deref, DerefMut)]
84
struct Velocity(Vec2);
85
86
#[derive(Event)]
87
struct BallCollided;
88
89
#[derive(Component)]
90
struct Brick;
91
92
#[derive(Resource, Deref)]
93
struct CollisionSound(Handle<AudioSource>);
94
95
// Default must be implemented to define this as a required component for the Wall component below
96
#[derive(Component, Default)]
97
struct Collider;
98
99
// This is a collection of the components that define a "Wall" in our game
100
#[derive(Component)]
101
#[require(Sprite, Transform, Collider)]
102
struct Wall;
103
104
/// Which side of the arena is this wall located on?
105
enum WallLocation {
106
Left,
107
Right,
108
Bottom,
109
Top,
110
}
111
112
impl WallLocation {
113
/// Location of the *center* of the wall, used in `transform.translation()`
114
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
/// (x, y) dimensions of the wall, used in `transform.scale()`
124
fn size(&self) -> Vec2 {
125
let arena_height = TOP_WALL - BOTTOM_WALL;
126
let arena_width = RIGHT_WALL - LEFT_WALL;
127
// Make sure we haven't messed up our constants
128
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
142
impl Wall {
143
// This "builder method" allows us to reuse logic across our wall entities,
144
// making our code easier to read and less prone to bugs when we change the logic
145
// Notice the use of Sprite and Transform alongside Wall, overwriting the default values defined for the required components
146
fn new(location: WallLocation) -> (Wall, Sprite, Transform) {
147
(
148
Wall,
149
Sprite::from_color(WALL_COLOR, Vec2::ONE),
150
Transform {
151
// We need to convert our Vec2 into a Vec3, by giving it a z-coordinate
152
// This is used to determine the order of our sprites
153
translation: location.position().extend(0.0),
154
// The z-scale of 2D objects must always be 1.0,
155
// or their ordering will be affected in surprising ways.
156
// See https://github.com/bevyengine/bevy/issues/4149
157
scale: location.size().extend(1.0),
158
..default()
159
},
160
)
161
}
162
}
163
164
// This resource tracks the game's score
165
#[derive(Resource, Deref, DerefMut)]
166
struct Score(usize);
167
168
#[derive(Component)]
169
struct ScoreboardUi;
170
171
// Add the game's entities to our world
172
fn setup(
173
mut commands: Commands,
174
mut meshes: ResMut<Assets<Mesh>>,
175
mut materials: ResMut<Assets<ColorMaterial>>,
176
asset_server: Res<AssetServer>,
177
) {
178
// Camera
179
commands.spawn(Camera2d);
180
181
// Sound
182
let ball_collision_sound = asset_server.load("sounds/breakout_collision.ogg");
183
commands.insert_resource(CollisionSound(ball_collision_sound));
184
185
// Paddle
186
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
// Ball
200
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
// Scoreboard
210
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
// Walls
235
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
// Bricks
241
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
// Given the space available, compute how many rows and columns of bricks we can fit
249
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
// Because we need to round the number of columns,
254
// the space on the top and sides of the bricks only captures a lower bound, not an exact value
255
let center_of_bricks = (LEFT_WALL + RIGHT_WALL) / 2.0;
256
let left_edge_of_bricks = center_of_bricks
257
// Space taken up by the bricks
258
- (n_columns as f32 / 2.0 * BRICK_SIZE.x)
259
// Space taken up by the gaps
260
- n_vertical_gaps as f32 / 2.0 * GAP_BETWEEN_BRICKS;
261
262
// In Bevy, the `translation` of an entity describes the center point,
263
// not its bottom-left corner
264
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
// brick
275
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
292
fn 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
// Calculate the new horizontal paddle position based on player input
308
let new_paddle_position =
309
paddle_transform.translation.x + direction * PADDLE_SPEED * time.delta_secs();
310
311
// Update the paddle position,
312
// making sure it doesn't cause the paddle to leave the arena
313
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
319
fn 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
326
fn 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
334
fn 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
// Trigger observers of the "BallCollided" event
353
commands.trigger(BallCollided);
354
355
// Bricks should be despawned and increment the scoreboard on collision
356
if maybe_brick.is_some() {
357
commands.entity(collider_entity).despawn();
358
**score += 1;
359
}
360
361
// Reflect the ball's velocity when it collides
362
let mut reflect_x = false;
363
let mut reflect_y = false;
364
365
// Reflect only if the velocity is in the opposite direction of the collision
366
// This prevents the ball from getting stuck inside the bar
367
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
// Reflect velocity on the x-axis if we hit something on the x-axis
375
if reflect_x {
376
ball_velocity.x = -ball_velocity.x;
377
}
378
379
// Reflect velocity on the y-axis if we hit something on the y-axis
380
if reflect_y {
381
ball_velocity.y = -ball_velocity.y;
382
}
383
}
384
}
385
}
386
387
fn 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)]
396
enum Collision {
397
Left,
398
Right,
399
Top,
400
Bottom,
401
}
402
403
// Returns `Some` if `ball` collides with `bounding_box`.
404
// The returned `Collision` is the side of `bounding_box` that `ball` hit.
405
fn 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
}
426
427