Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/examples/games/breakout.rs
6592 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: f32 = 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
.add_schedule(FixedUpdate)
60
.at(percent(35), percent(50)),
61
)
62
.insert_resource(Score(0))
63
.insert_resource(ClearColor(BACKGROUND_COLOR))
64
.add_event::<CollisionEvent>()
65
.add_systems(Startup, setup)
66
// Add our gameplay simulation systems to the fixed timestep schedule
67
// which runs at 64 Hz by default
68
.add_systems(
69
FixedUpdate,
70
(
71
apply_velocity,
72
move_paddle,
73
check_for_collisions,
74
play_collision_sound,
75
)
76
// `chain`ing systems together runs them in order
77
.chain(),
78
)
79
.add_systems(Update, update_scoreboard)
80
.run();
81
}
82
83
#[derive(Component)]
84
struct Paddle;
85
86
#[derive(Component)]
87
struct Ball;
88
89
#[derive(Component, Deref, DerefMut)]
90
struct Velocity(Vec2);
91
92
#[derive(BufferedEvent, Default)]
93
struct CollisionEvent;
94
95
#[derive(Component)]
96
struct Brick;
97
98
#[derive(Resource, Deref)]
99
struct CollisionSound(Handle<AudioSource>);
100
101
// Default must be implemented to define this as a required component for the Wall component below
102
#[derive(Component, Default)]
103
struct Collider;
104
105
// This is a collection of the components that define a "Wall" in our game
106
#[derive(Component)]
107
#[require(Sprite, Transform, Collider)]
108
struct Wall;
109
110
/// Which side of the arena is this wall located on?
111
enum WallLocation {
112
Left,
113
Right,
114
Bottom,
115
Top,
116
}
117
118
impl WallLocation {
119
/// Location of the *center* of the wall, used in `transform.translation()`
120
fn position(&self) -> Vec2 {
121
match self {
122
WallLocation::Left => Vec2::new(LEFT_WALL, 0.),
123
WallLocation::Right => Vec2::new(RIGHT_WALL, 0.),
124
WallLocation::Bottom => Vec2::new(0., BOTTOM_WALL),
125
WallLocation::Top => Vec2::new(0., TOP_WALL),
126
}
127
}
128
129
/// (x, y) dimensions of the wall, used in `transform.scale()`
130
fn size(&self) -> Vec2 {
131
let arena_height = TOP_WALL - BOTTOM_WALL;
132
let arena_width = RIGHT_WALL - LEFT_WALL;
133
// Make sure we haven't messed up our constants
134
assert!(arena_height > 0.0);
135
assert!(arena_width > 0.0);
136
137
match self {
138
WallLocation::Left | WallLocation::Right => {
139
Vec2::new(WALL_THICKNESS, arena_height + WALL_THICKNESS)
140
}
141
WallLocation::Bottom | WallLocation::Top => {
142
Vec2::new(arena_width + WALL_THICKNESS, WALL_THICKNESS)
143
}
144
}
145
}
146
}
147
148
impl Wall {
149
// This "builder method" allows us to reuse logic across our wall entities,
150
// making our code easier to read and less prone to bugs when we change the logic
151
// Notice the use of Sprite and Transform alongside Wall, overwriting the default values defined for the required components
152
fn new(location: WallLocation) -> (Wall, Sprite, Transform) {
153
(
154
Wall,
155
Sprite::from_color(WALL_COLOR, Vec2::ONE),
156
Transform {
157
// We need to convert our Vec2 into a Vec3, by giving it a z-coordinate
158
// This is used to determine the order of our sprites
159
translation: location.position().extend(0.0),
160
// The z-scale of 2D objects must always be 1.0,
161
// or their ordering will be affected in surprising ways.
162
// See https://github.com/bevyengine/bevy/issues/4149
163
scale: location.size().extend(1.0),
164
..default()
165
},
166
)
167
}
168
}
169
170
// This resource tracks the game's score
171
#[derive(Resource, Deref, DerefMut)]
172
struct Score(usize);
173
174
#[derive(Component)]
175
struct ScoreboardUi;
176
177
// Add the game's entities to our world
178
fn setup(
179
mut commands: Commands,
180
mut meshes: ResMut<Assets<Mesh>>,
181
mut materials: ResMut<Assets<ColorMaterial>>,
182
asset_server: Res<AssetServer>,
183
) {
184
// Camera
185
commands.spawn(Camera2d);
186
187
// Sound
188
let ball_collision_sound = asset_server.load("sounds/breakout_collision.ogg");
189
commands.insert_resource(CollisionSound(ball_collision_sound));
190
191
// Paddle
192
let paddle_y = BOTTOM_WALL + GAP_BETWEEN_PADDLE_AND_FLOOR;
193
194
commands.spawn((
195
Sprite::from_color(PADDLE_COLOR, Vec2::ONE),
196
Transform {
197
translation: Vec3::new(0.0, paddle_y, 0.0),
198
scale: PADDLE_SIZE.extend(1.0),
199
..default()
200
},
201
Paddle,
202
Collider,
203
));
204
205
// Ball
206
commands.spawn((
207
Mesh2d(meshes.add(Circle::default())),
208
MeshMaterial2d(materials.add(BALL_COLOR)),
209
Transform::from_translation(BALL_STARTING_POSITION)
210
.with_scale(Vec2::splat(BALL_DIAMETER).extend(1.)),
211
Ball,
212
Velocity(INITIAL_BALL_DIRECTION.normalize() * BALL_SPEED),
213
));
214
215
// Scoreboard
216
commands.spawn((
217
Text::new("Score: "),
218
TextFont {
219
font_size: SCOREBOARD_FONT_SIZE,
220
..default()
221
},
222
TextColor(TEXT_COLOR),
223
ScoreboardUi,
224
Node {
225
position_type: PositionType::Absolute,
226
top: SCOREBOARD_TEXT_PADDING,
227
left: SCOREBOARD_TEXT_PADDING,
228
..default()
229
},
230
children![(
231
TextSpan::default(),
232
TextFont {
233
font_size: SCOREBOARD_FONT_SIZE,
234
..default()
235
},
236
TextColor(SCORE_COLOR),
237
)],
238
));
239
240
// Walls
241
commands.spawn(Wall::new(WallLocation::Left));
242
commands.spawn(Wall::new(WallLocation::Right));
243
commands.spawn(Wall::new(WallLocation::Bottom));
244
commands.spawn(Wall::new(WallLocation::Top));
245
246
// Bricks
247
let total_width_of_bricks = (RIGHT_WALL - LEFT_WALL) - 2. * GAP_BETWEEN_BRICKS_AND_SIDES;
248
let bottom_edge_of_bricks = paddle_y + GAP_BETWEEN_PADDLE_AND_BRICKS;
249
let total_height_of_bricks = TOP_WALL - bottom_edge_of_bricks - GAP_BETWEEN_BRICKS_AND_CEILING;
250
251
assert!(total_width_of_bricks > 0.0);
252
assert!(total_height_of_bricks > 0.0);
253
254
// Given the space available, compute how many rows and columns of bricks we can fit
255
let n_columns = (total_width_of_bricks / (BRICK_SIZE.x + GAP_BETWEEN_BRICKS)).floor() as usize;
256
let n_rows = (total_height_of_bricks / (BRICK_SIZE.y + GAP_BETWEEN_BRICKS)).floor() as usize;
257
let n_vertical_gaps = n_columns - 1;
258
259
// Because we need to round the number of columns,
260
// the space on the top and sides of the bricks only captures a lower bound, not an exact value
261
let center_of_bricks = (LEFT_WALL + RIGHT_WALL) / 2.0;
262
let left_edge_of_bricks = center_of_bricks
263
// Space taken up by the bricks
264
- (n_columns as f32 / 2.0 * BRICK_SIZE.x)
265
// Space taken up by the gaps
266
- n_vertical_gaps as f32 / 2.0 * GAP_BETWEEN_BRICKS;
267
268
// In Bevy, the `translation` of an entity describes the center point,
269
// not its bottom-left corner
270
let offset_x = left_edge_of_bricks + BRICK_SIZE.x / 2.;
271
let offset_y = bottom_edge_of_bricks + BRICK_SIZE.y / 2.;
272
273
for row in 0..n_rows {
274
for column in 0..n_columns {
275
let brick_position = Vec2::new(
276
offset_x + column as f32 * (BRICK_SIZE.x + GAP_BETWEEN_BRICKS),
277
offset_y + row as f32 * (BRICK_SIZE.y + GAP_BETWEEN_BRICKS),
278
);
279
280
// brick
281
commands.spawn((
282
Sprite {
283
color: BRICK_COLOR,
284
..default()
285
},
286
Transform {
287
translation: brick_position.extend(0.0),
288
scale: Vec3::new(BRICK_SIZE.x, BRICK_SIZE.y, 1.0),
289
..default()
290
},
291
Brick,
292
Collider,
293
));
294
}
295
}
296
}
297
298
fn move_paddle(
299
keyboard_input: Res<ButtonInput<KeyCode>>,
300
mut paddle_transform: Single<&mut Transform, With<Paddle>>,
301
time: Res<Time>,
302
) {
303
let mut direction = 0.0;
304
305
if keyboard_input.pressed(KeyCode::ArrowLeft) {
306
direction -= 1.0;
307
}
308
309
if keyboard_input.pressed(KeyCode::ArrowRight) {
310
direction += 1.0;
311
}
312
313
// Calculate the new horizontal paddle position based on player input
314
let new_paddle_position =
315
paddle_transform.translation.x + direction * PADDLE_SPEED * time.delta_secs();
316
317
// Update the paddle position,
318
// making sure it doesn't cause the paddle to leave the arena
319
let left_bound = LEFT_WALL + WALL_THICKNESS / 2.0 + PADDLE_SIZE.x / 2.0 + PADDLE_PADDING;
320
let right_bound = RIGHT_WALL - WALL_THICKNESS / 2.0 - PADDLE_SIZE.x / 2.0 - PADDLE_PADDING;
321
322
paddle_transform.translation.x = new_paddle_position.clamp(left_bound, right_bound);
323
}
324
325
fn apply_velocity(mut query: Query<(&mut Transform, &Velocity)>, time: Res<Time>) {
326
for (mut transform, velocity) in &mut query {
327
transform.translation.x += velocity.x * time.delta_secs();
328
transform.translation.y += velocity.y * time.delta_secs();
329
}
330
}
331
332
fn update_scoreboard(
333
score: Res<Score>,
334
score_root: Single<Entity, (With<ScoreboardUi>, With<Text>)>,
335
mut writer: TextUiWriter,
336
) {
337
*writer.text(*score_root, 1) = score.to_string();
338
}
339
340
fn check_for_collisions(
341
mut commands: Commands,
342
mut score: ResMut<Score>,
343
ball_query: Single<(&mut Velocity, &Transform), With<Ball>>,
344
collider_query: Query<(Entity, &Transform, Option<&Brick>), With<Collider>>,
345
mut collision_events: EventWriter<CollisionEvent>,
346
) {
347
let (mut ball_velocity, ball_transform) = ball_query.into_inner();
348
349
for (collider_entity, collider_transform, maybe_brick) in &collider_query {
350
let collision = ball_collision(
351
BoundingCircle::new(ball_transform.translation.truncate(), BALL_DIAMETER / 2.),
352
Aabb2d::new(
353
collider_transform.translation.truncate(),
354
collider_transform.scale.truncate() / 2.,
355
),
356
);
357
358
if let Some(collision) = collision {
359
// Writes a collision event so that other systems can react to the collision
360
collision_events.write_default();
361
362
// Bricks should be despawned and increment the scoreboard on collision
363
if maybe_brick.is_some() {
364
commands.entity(collider_entity).despawn();
365
**score += 1;
366
}
367
368
// Reflect the ball's velocity when it collides
369
let mut reflect_x = false;
370
let mut reflect_y = false;
371
372
// Reflect only if the velocity is in the opposite direction of the collision
373
// This prevents the ball from getting stuck inside the bar
374
match collision {
375
Collision::Left => reflect_x = ball_velocity.x > 0.0,
376
Collision::Right => reflect_x = ball_velocity.x < 0.0,
377
Collision::Top => reflect_y = ball_velocity.y < 0.0,
378
Collision::Bottom => reflect_y = ball_velocity.y > 0.0,
379
}
380
381
// Reflect velocity on the x-axis if we hit something on the x-axis
382
if reflect_x {
383
ball_velocity.x = -ball_velocity.x;
384
}
385
386
// Reflect velocity on the y-axis if we hit something on the y-axis
387
if reflect_y {
388
ball_velocity.y = -ball_velocity.y;
389
}
390
}
391
}
392
}
393
394
fn play_collision_sound(
395
mut commands: Commands,
396
mut collision_events: EventReader<CollisionEvent>,
397
sound: Res<CollisionSound>,
398
) {
399
// Play a sound once per frame if a collision occurred.
400
if !collision_events.is_empty() {
401
// This prevents events staying active on the next frame.
402
collision_events.clear();
403
commands.spawn((AudioPlayer(sound.clone()), PlaybackSettings::DESPAWN));
404
}
405
}
406
407
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
408
enum Collision {
409
Left,
410
Right,
411
Top,
412
Bottom,
413
}
414
415
// Returns `Some` if `ball` collides with `bounding_box`.
416
// The returned `Collision` is the side of `bounding_box` that `ball` hit.
417
fn ball_collision(ball: BoundingCircle, bounding_box: Aabb2d) -> Option<Collision> {
418
if !ball.intersects(&bounding_box) {
419
return None;
420
}
421
422
let closest = bounding_box.closest_point(ball.center());
423
let offset = ball.center() - closest;
424
let side = if offset.x.abs() > offset.y.abs() {
425
if offset.x < 0. {
426
Collision::Left
427
} else {
428
Collision::Right
429
}
430
} else if offset.y > 0. {
431
Collision::Top
432
} else {
433
Collision::Bottom
434
};
435
436
Some(side)
437
}
438
439