Skip to content

Commit

Permalink
fix examples
Browse files Browse the repository at this point in the history
  • Loading branch information
maniwani committed Jul 29, 2022
1 parent ff44dc8 commit 3f8cdda
Show file tree
Hide file tree
Showing 11 changed files with 85 additions and 60 deletions.
17 changes: 11 additions & 6 deletions examples/2d/rotation.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
//! Demonstrates rotating entities in 2D using quaternions.
use bevy::{math::Vec3Swizzles, prelude::*, time::FixedTimestep};
use bevy::{math::Vec3Swizzles, prelude::*};

const TIME_STEP: f32 = 1.0 / 60.0;
const BOUNDS: Vec2 = Vec2::new(1200.0, 640.0);

fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(|mut fixed_time: ResMut<FixedTime>| {
fixed_time.set_steps_per_second(60.0);
})
.add_startup_system(setup)
.add_system_set(
SystemSet::new()
.with_run_criteria(FixedTimestep::step(TIME_STEP as f64))
.with_run_criteria(FixedTimestep::step)
.with_system(player_movement_system)
.with_system(snap_to_player_system)
.with_system(rotate_to_player_system),
Expand Down Expand Up @@ -110,6 +112,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {

/// Demonstrates applying rotation and movement based on keyboard input.
fn player_movement_system(
fixed_time: Res<FixedTime>,
keyboard_input: Res<Input<KeyCode>>,
mut query: Query<(&Player, &mut Transform)>,
) {
Expand All @@ -131,12 +134,12 @@ fn player_movement_system(
}

// update the ship rotation around the Z axis (perpendicular to the 2D plane of the screen)
transform.rotate_z(rotation_factor * ship.rotation_speed * TIME_STEP);
transform.rotate_z(rotation_factor * ship.rotation_speed * fixed_time.delta_seconds());

// get the ship's forward vector by applying the current rotation to the ships initial facing vector
let movement_direction = transform.rotation * Vec3::Y;
// get the distance the ship will move based on direction, the ship's movement speed and delta time
let movement_distance = movement_factor * ship.movement_speed * TIME_STEP;
let movement_distance = movement_factor * ship.movement_speed * fixed_time.delta_seconds();
// create the change in translation using the new movement direction and distance
let translation_delta = movement_direction * movement_distance;
// update the ship translation with our new translation delta
Expand Down Expand Up @@ -191,6 +194,7 @@ fn snap_to_player_system(
/// floating point precision loss, so it pays to clamp your dot product value before calling
/// `acos`.
fn rotate_to_player_system(
fixed_time: Res<FixedTime>,
mut query: Query<(&RotateToPlayer, &mut Transform), Without<Player>>,
player_query: Query<&Transform, With<Player>>,
) {
Expand Down Expand Up @@ -235,7 +239,8 @@ fn rotate_to_player_system(
let max_angle = forward_dot_player.clamp(-1.0, 1.0).acos(); // clamp acos for safety

// calculate angle of rotation with limit
let rotation_angle = rotation_sign * (config.rotation_speed * TIME_STEP).min(max_angle);
let rotation_angle =
rotation_sign * (config.rotation_speed * fixed_time.delta_seconds()).min(max_angle);

// rotate the enemy to face the player
enemy_transform.rotate_z(rotation_angle);
Expand Down
2 changes: 1 addition & 1 deletion examples/3d/transparency_3d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ fn setup(
/// when the alpha value goes back below the threshold.
/// - `Blend`: Object fades in and out smoothly.
pub fn fade_transparency(time: Res<Time>, mut materials: ResMut<Assets<StandardMaterial>>) {
let alpha = (time.time_since_startup().as_secs_f32().sin() / 2.0) + 0.5;
let alpha = (time.seconds_since_startup().sin() / 2.0) + 0.5;
for (_, material) in materials.iter_mut() {
material.base_color.set_a(alpha);
}
Expand Down
6 changes: 2 additions & 4 deletions examples/animation/custom_skinned_mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,7 @@ fn setup(
/// Animate the joint marked with [`AnimatedJoint`] component.
fn joint_animation(time: Res<Time>, mut query: Query<&mut Transform, With<AnimatedJoint>>) {
for mut transform in &mut query {
transform.rotation = Quat::from_axis_angle(
Vec3::Z,
0.5 * PI * time.time_since_startup().as_secs_f32().sin(),
);
transform.rotation =
Quat::from_axis_angle(Vec3::Z, 0.5 * PI * time.seconds_since_startup().sin());
}
}
6 changes: 2 additions & 4 deletions examples/animation/gltf_skinned_mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,7 @@ fn joint_animation(
// Get `Transform` in the second joint.
let mut second_joint_transform = transform_query.get_mut(second_joint_entity).unwrap();

second_joint_transform.rotation = Quat::from_axis_angle(
Vec3::Z,
0.5 * PI * time.time_since_startup().as_secs_f32().sin(),
);
second_joint_transform.rotation =
Quat::from_axis_angle(Vec3::Z, 0.5 * PI * time.seconds_since_startup().sin());
}
}
2 changes: 1 addition & 1 deletion examples/ecs/component_change_detection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn main() {
}

#[derive(Component, Debug)]
struct MyComponent(f64);
struct MyComponent(f32);

fn setup(mut commands: Commands) {
commands.spawn().insert(MyComponent(0.));
Expand Down
51 changes: 27 additions & 24 deletions examples/ecs/fixed_timestep.rs
Original file line number Diff line number Diff line change
@@ -1,52 +1,55 @@
//! Shows how to create systems that run every fixed timestep, rather than every tick.
use bevy::{
prelude::*,
time::{FixedTimestep, FixedTimesteps},
};

const LABEL: &str = "my_fixed_timestep";
use bevy::prelude::*;

#[derive(Debug, Hash, PartialEq, Eq, Clone, StageLabel)]
struct FixedUpdateStage;

fn main() {
App::new()
.add_plugins(DefaultPlugins)
// this system will run once every update (it should match your screen's refresh rate)
.add_startup_system(|mut fixed_time: ResMut<FixedTime>| {
fixed_time.set_steps_per_second(10.0);
})
// Add a system that runs once per update (which should match your screen's refresh rate).
.add_system(frame_update)
// add a new stage that runs twice a second
// Add a new stage that runs ten times per second.
.add_stage_after(
CoreStage::Update,
FixedUpdateStage,
SystemStage::parallel()
.with_run_criteria(
FixedTimestep::step(0.5)
// labels are optional. they provide a way to access the current
// FixedTimestep state from within a system
.with_label(LABEL),
)
.with_run_criteria(FixedTimestep::step)
.with_system(fixed_update),
)
.run();
}

fn frame_update(mut last_time: Local<f64>, time: Res<Time>) {
info!("update: {}", time.seconds_since_startup() - *last_time);
fn frame_update(mut last_time: Local<f32>, time: Res<Time>) {
info!(
"time since last frame_update: {}",
time.seconds_since_startup() - *last_time
);
*last_time = time.seconds_since_startup();
}

fn fixed_update(mut last_time: Local<f64>, time: Res<Time>, fixed_timesteps: Res<FixedTimesteps>) {
fn fixed_update(
mut last_time: Local<f32>,
time: Res<Time>,
fixed_time: Res<FixedTime>,
accumulator: Res<FixedTimestepState>,
) {
info!(
"fixed_update: {}",
time.seconds_since_startup() - *last_time,
"time since last fixed_update: {}\n",
time.seconds_since_startup() - *last_time
);

let fixed_timestep = fixed_timesteps.get(LABEL).unwrap();
info!("fixed timestep: {}\n", fixed_time.delta_seconds());
info!(
" overstep_percentage: {}",
fixed_timestep.overstep_percentage()
"time accrued toward next fixed_update: {}\n",
accumulator.overstep().as_secs_f32()
);
info!(
"time accrued toward next fixed_update (% of timestep): {}",
accumulator.overstep_percentage(fixed_time.delta())
);

*last_time = time.seconds_since_startup();
}
17 changes: 11 additions & 6 deletions examples/ecs/iter_combinations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,22 @@ use rand::{thread_rng, Rng};
#[derive(Debug, Hash, PartialEq, Eq, Clone, StageLabel)]
struct FixedUpdateStage;

const DELTA_TIME: f64 = 0.01;

fn main() {
App::new()
.add_plugins(DefaultPlugins)
.insert_resource(AmbientLight {
brightness: 0.03,
..default()
})
.add_startup_system(|mut fixed_time: ResMut<FixedTime>| {
fixed_time.set_steps_per_second(10.0);
})
.add_startup_system(generate_bodies)
.add_stage_after(
CoreStage::Update,
FixedUpdateStage,
SystemStage::parallel()
.with_run_criteria(FixedTimestep::step(DELTA_TIME))
.with_run_criteria(FixedTimestep::step)
.with_system(interact_bodies)
.with_system(integrate),
)
Expand Down Expand Up @@ -54,6 +55,7 @@ fn generate_bodies(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
fixed_time: Res<FixedTime>,
) {
let mesh = meshes.add(Mesh::from(shape::Icosphere {
radius: 1.0,
Expand Down Expand Up @@ -103,7 +105,7 @@ fn generate_bodies(
rng.gen_range(vel_range.clone()),
rng.gen_range(vel_range.clone()),
rng.gen_range(vel_range.clone()),
) * DELTA_TIME as f32,
) * fixed_time.delta_seconds(),
),
});
}
Expand Down Expand Up @@ -162,8 +164,11 @@ fn interact_bodies(mut query: Query<(&Mass, &GlobalTransform, &mut Acceleration)
}
}

fn integrate(mut query: Query<(&mut Acceleration, &mut Transform, &mut LastPos)>) {
let dt_sq = (DELTA_TIME * DELTA_TIME) as f32;
fn integrate(
fixed_time: Res<FixedTime>,
mut query: Query<(&mut Acceleration, &mut Transform, &mut LastPos)>,
) {
let dt_sq = fixed_time.delta_seconds() * fixed_time.delta_seconds();
for (mut acceleration, mut transform, mut last_pos) in &mut query {
// verlet integration
// x(t+dt) = 2x(t) - x(t-dt) + a(t)dt^2 + O(dt^4)
Expand Down
16 changes: 14 additions & 2 deletions examples/games/alien_cake_addict.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Eat the cakes. Eat them all. An example 3D game.
use bevy::{ecs::schedule::SystemSet, prelude::*, time::FixedTimestep};
use bevy::ecs::schedule::ShouldRun;
use bevy::prelude::*;
use rand::Rng;

#[derive(Clone, Eq, PartialEq, Debug, Hash)]
Expand All @@ -9,9 +10,12 @@ enum GameState {
GameOver,
}

struct SpawnTimer(Timer);

fn main() {
App::new()
.init_resource::<Game>()
.insert_resource(SpawnTimer(Timer::from_seconds(5.0, false)))
.add_plugins(DefaultPlugins)
.add_state(GameState::Playing)
.add_startup_system(setup_cameras)
Expand All @@ -29,7 +33,15 @@ fn main() {
.add_system_set(SystemSet::on_exit(GameState::GameOver).with_system(teardown))
.add_system_set(
SystemSet::new()
.with_run_criteria(FixedTimestep::step(5.0))
.with_run_criteria(|time: Res<Time>, mut timer: ResMut<SpawnTimer>| {
timer.0.tick(time.delta());
if timer.0.finished() {
timer.0.reset();
ShouldRun::Yes
} else {
ShouldRun::No
}
})
.with_system(spawn_bonus),
)
.add_system(bevy::window::close_on_esc)
Expand Down
19 changes: 10 additions & 9 deletions examples/games/breakout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,8 @@
use bevy::{
prelude::*,
sprite::collide_aabb::{collide, Collision},
time::FixedTimestep,
};

// Defines the amount of time that should elapse between each physics step.
const TIME_STEP: f32 = 1.0 / 60.0;

// These constants are defined in `Transform` units.
// Using the default 2D camera they correspond 1:1 with screen pixels.
const PADDLE_SIZE: Vec3 = Vec3::new(120.0, 20.0, 0.0);
Expand Down Expand Up @@ -55,11 +51,14 @@ fn main() {
.add_plugins(DefaultPlugins)
.insert_resource(Scoreboard { score: 0 })
.insert_resource(ClearColor(BACKGROUND_COLOR))
.add_startup_system(|mut fixed_time: ResMut<FixedTime>| {
fixed_time.set_steps_per_second(60.0);
})
.add_startup_system(setup)
.add_event::<CollisionEvent>()
.add_system_set(
SystemSet::new()
.with_run_criteria(FixedTimestep::step(TIME_STEP as f64))
.with_run_criteria(FixedTimestep::step)
.with_system(check_for_collisions)
.with_system(move_paddle.before(check_for_collisions))
.with_system(apply_velocity.before(check_for_collisions))
Expand Down Expand Up @@ -310,6 +309,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
}

fn move_paddle(
fixed_time: Res<FixedTime>,
keyboard_input: Res<Input<KeyCode>>,
mut query: Query<&mut Transform, With<Paddle>>,
) {
Expand All @@ -325,7 +325,8 @@ fn move_paddle(
}

// Calculate the new horizontal paddle position based on player input
let new_paddle_position = paddle_transform.translation.x + direction * PADDLE_SPEED * TIME_STEP;
let new_paddle_position =
paddle_transform.translation.x + direction * PADDLE_SPEED * fixed_time.delta_seconds();

// Update the paddle position,
// making sure it doesn't cause the paddle to leave the arena
Expand All @@ -335,10 +336,10 @@ fn move_paddle(
paddle_transform.translation.x = new_paddle_position.clamp(left_bound, right_bound);
}

fn apply_velocity(mut query: Query<(&mut Transform, &Velocity)>) {
fn apply_velocity(fixed_time: Res<FixedTime>, mut query: Query<(&mut Transform, &Velocity)>) {
for (mut transform, velocity) in &mut query {
transform.translation.x += velocity.x * TIME_STEP;
transform.translation.y += velocity.y * TIME_STEP;
transform.translation.x += velocity.x * fixed_time.delta_seconds();
transform.translation.y += velocity.y * fixed_time.delta_seconds();
}
}

Expand Down
2 changes: 1 addition & 1 deletion examples/scene/scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ impl FromWorld for ComponentB {
fn from_world(world: &mut World) -> Self {
let time = world.resource::<Time>();
ComponentB {
_time_since_startup: time.time_since_startup(),
_time_since_startup: time.elapsed_since_startup(),
value: "Default Value".to_string(),
}
}
Expand Down
7 changes: 5 additions & 2 deletions examples/stress_tests/bevymark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
use bevy::{
diagnostic::{Diagnostics, FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
prelude::*,
time::FixedTimestep,
time::{FixedTime, FixedTimestep},
window::PresentMode,
};
use rand::{thread_rng, Rng};
Expand Down Expand Up @@ -43,14 +43,17 @@ fn main() {
count: 0,
color: Color::WHITE,
})
.add_startup_system(|mut fixed_time: ResMut<FixedTime>| {
fixed_time.set_steps_per_second(5.0);
})
.add_startup_system(setup)
.add_system(mouse_handler)
.add_system(movement_system)
.add_system(collision_system)
.add_system(counter_system)
.add_system_set(
SystemSet::new()
.with_run_criteria(FixedTimestep::step(0.2))
.with_run_criteria(FixedTimestep::step)
.with_system(scheduled_spawner),
)
.run();
Expand Down

0 comments on commit 3f8cdda

Please sign in to comment.