Skip to content

Commit 9186c4c

Browse files
hymmcart
andcommitted
Change breakout to use fixed timestamp (#1541)
This PR fixes #1240, where the ball is escaping the playing field at low framerates. I did this by moving the movement and physics system into a Fixed Timestep system set and changing the movement steps to a constant. So we lose the example use of delta_time for changing position, but gain a use of FixedTimestep. If this is accepted bevyengine/bevy-website#102 will need to be updated to match. Co-authored-by: Carter Anderson <[email protected]>
1 parent 60f286d commit 9186c4c

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

examples/game/breakout.rs

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,25 @@
11
use bevy::{
2+
core::FixedTimestep,
23
prelude::*,
34
render::pass::ClearColor,
45
sprite::collide_aabb::{collide, Collision},
56
};
67

78
/// An implementation of the classic game "Breakout"
9+
const TIME_STEP: f32 = 1.0 / 60.0;
810
fn main() {
911
App::build()
1012
.add_plugins(DefaultPlugins)
1113
.insert_resource(Scoreboard { score: 0 })
1214
.insert_resource(ClearColor(Color::rgb(0.9, 0.9, 0.9)))
1315
.add_startup_system(setup.system())
14-
.add_system(paddle_movement_system.system())
15-
.add_system(ball_collision_system.system())
16-
.add_system(ball_movement_system.system())
16+
.add_system_set(
17+
SystemSet::new()
18+
.with_run_criteria(FixedTimestep::step(TIME_STEP as f64))
19+
.with_system(paddle_movement_system.system())
20+
.with_system(ball_collision_system.system())
21+
.with_system(ball_movement_system.system()),
22+
)
1723
.add_system(scoreboard_system.system())
1824
.run();
1925
}
@@ -175,7 +181,6 @@ fn setup(
175181
}
176182

177183
fn paddle_movement_system(
178-
time: Res<Time>,
179184
keyboard_input: Res<Input<KeyCode>>,
180185
mut query: Query<(&Paddle, &mut Transform)>,
181186
) {
@@ -191,18 +196,15 @@ fn paddle_movement_system(
191196

192197
let translation = &mut transform.translation;
193198
// move the paddle horizontally
194-
translation.x += time.delta_seconds() * direction * paddle.speed;
199+
translation.x += direction * paddle.speed * TIME_STEP;
195200
// bound the paddle within the walls
196201
translation.x = translation.x.min(380.0).max(-380.0);
197202
}
198203
}
199204

200-
fn ball_movement_system(time: Res<Time>, mut ball_query: Query<(&Ball, &mut Transform)>) {
201-
// clamp the timestep to stop the ball from escaping when the game starts
202-
let delta_seconds = f32::min(0.2, time.delta_seconds());
203-
205+
fn ball_movement_system(mut ball_query: Query<(&Ball, &mut Transform)>) {
204206
if let Ok((ball, mut transform)) = ball_query.single_mut() {
205-
transform.translation += ball.velocity * delta_seconds;
207+
transform.translation += ball.velocity * TIME_STEP;
206208
}
207209
}
208210

0 commit comments

Comments
 (0)