Skip to content

Commit

Permalink
fix examples
Browse files Browse the repository at this point in the history
  • Loading branch information
maniwani committed Mar 31, 2022
1 parent ed7b4f8 commit 1441afd
Show file tree
Hide file tree
Showing 15 changed files with 98 additions and 61 deletions.
16 changes: 11 additions & 5 deletions examples/2d/rotation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn main() {
.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 @@ -51,7 +51,9 @@ struct RotateToPlayer {
/// * Z axis goes from far to near (+Z points towards you, out of the screen)
///
/// The origin is at the center of the screen.
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
fn setup(mut commands: Commands, mut time: ResMut<FixedTime>, asset_server: Res<AssetServer>) {
time.set_delta_seconds(TIME_STEP);

let ship_handle = asset_server.load("textures/simplespace/ship_C.png");
let enemy_a_handle = asset_server.load("textures/simplespace/enemy_A.png");
let enemy_b_handle = asset_server.load("textures/simplespace/enemy_B.png");
Expand Down Expand Up @@ -112,6 +114,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {

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

// create the change in rotation around the Z axis (perpendicular to the 2D plane of the screen)
let rotation_delta = Quat::from_rotation_z(rotation_factor * ship.rotation_speed * TIME_STEP);
let rotation_delta =
Quat::from_rotation_z(rotation_factor * ship.rotation_speed * time.delta_seconds());
// update the ship rotation with our rotation delta
transform.rotation *= rotation_delta;

// 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 * 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 @@ -195,6 +199,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(
time: Res<FixedTime>,
mut query: Query<(&RotateToPlayer, &mut Transform), Without<Player>>,
player_query: Query<&Transform, With<Player>>,
) {
Expand Down Expand Up @@ -239,7 +244,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 * time.delta_seconds()).min(max_angle);

// get the quaternion to rotate from the current enemy facing direction towards the
// direction facing the player
Expand Down
8 changes: 4 additions & 4 deletions examples/2d/text2d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ fn animate_translation(
mut query: Query<&mut Transform, (With<Text>, With<AnimateTranslation>)>,
) {
for mut transform in query.iter_mut() {
transform.translation.x = 100.0 * time.seconds_since_startup().sin() as f32 - 400.0;
transform.translation.y = 100.0 * time.seconds_since_startup().cos() as f32;
transform.translation.x = 100.0 * time.seconds_since_startup().sin() - 400.0;
transform.translation.y = 100.0 * time.seconds_since_startup().cos();
}
}

Expand All @@ -104,7 +104,7 @@ fn animate_rotation(
mut query: Query<&mut Transform, (With<Text>, With<AnimateRotation>)>,
) {
for mut transform in query.iter_mut() {
transform.rotation = Quat::from_rotation_z(time.seconds_since_startup().cos() as f32);
transform.rotation = Quat::from_rotation_z(time.seconds_since_startup().cos());
}
}

Expand All @@ -116,6 +116,6 @@ fn animate_scale(
// rendered quad, resulting in a pixellated look.
for mut transform in query.iter_mut() {
transform.translation = Vec3::new(400.0, 0.0, 0.0);
transform.scale = Vec3::splat((time.seconds_since_startup().sin() as f32 + 1.1) * 2.0);
transform.scale = Vec3::splat((time.seconds_since_startup().sin() + 1.1) * 2.0);
}
}
12 changes: 8 additions & 4 deletions examples/3d/manual_gltf_animation_player.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ fn main() {
.add_startup_system(setup)
.add_system_set(
SystemSet::new()
.with_run_criteria(FixedTimestep::step(10.0))
.with_run_criteria(FixedTimestep::step)
.with_system(switch_scene),
)
.add_system(setup_scene_once_loaded)
Expand Down Expand Up @@ -82,15 +82,19 @@ struct CurrentScene {
}

struct CurrentAnimation {
start_time: f64,
start_time: f32,
animation: GltfAnimation,
}

fn setup(
mut commands: Commands,
mut time: ResMut<FixedTime>,
asset_server: Res<AssetServer>,
mut scene_spawner: ResMut<SceneSpawner>,
) {
// Fixed timestep
time.set_delta_seconds(10.0);

// Insert a resource with the current scene information
commands.insert_resource(CurrentScene {
// Its instance id, to be able to check that it's loaded
Expand Down Expand Up @@ -174,8 +178,8 @@ fn gltf_animation_driver(
time: Res<Time>,
) {
if let Some(current_animation) = current_animation {
let elapsed = (time.seconds_since_startup() - current_animation.start_time) as f32
* current_scene.speed;
let elapsed =
(time.seconds_since_startup() - current_animation.start_time) * current_scene.speed;
for (mut transform, node) in animated.iter_mut() {
let node_animations = current_animation
.animation
Expand Down
12 changes: 6 additions & 6 deletions examples/3d/update_gltf_scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,15 +76,15 @@ fn move_scene_entities(
time: Res<Time>,
mut scene_entities: Query<&mut Transform, With<EntityInMyScene>>,
) {
let mut direction = 1.;
let mut scale = 1.;
let mut direction = 1.0;
let mut scale = 1.0;
for mut transform in scene_entities.iter_mut() {
transform.translation = Vec3::new(
scale * direction * time.seconds_since_startup().sin() as f32 / 20.,
0.,
time.seconds_since_startup().cos() as f32 / 20.,
scale * direction * time.seconds_since_startup().sin() / 20.0,
0.0,
time.seconds_since_startup().cos() / 20.0,
);
direction *= -1.;
direction *= -1.0;
scale += 0.5;
}
}
2 changes: 1 addition & 1 deletion examples/animation/custom_skinned_mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ fn joint_animation(time: Res<Time>, mut query: Query<&mut Transform, With<Animat
for mut transform in query.iter_mut() {
transform.rotation = Quat::from_axis_angle(
Vec3::Z,
0.5 * PI * time.time_since_startup().as_secs_f32().sin(),
0.5 * PI * time.seconds_since_startup().sin(),
);
}
}
2 changes: 1 addition & 1 deletion examples/animation/gltf_skinned_mesh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ fn joint_animation(

second_joint_transform.rotation = Quat::from_axis_angle(
Vec3::Z,
0.5 * PI * time.time_since_startup().as_secs_f32().sin(),
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 @@ -13,7 +13,7 @@ fn main() {
}

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

fn setup(mut commands: Commands) {
commands.spawn().insert(MyComponent(0.));
Expand Down
50 changes: 29 additions & 21 deletions examples/ecs/fixed_timestep.rs
Original file line number Diff line number Diff line change
@@ -1,50 +1,58 @@
use bevy::{
core::{FixedTimestep, FixedTimesteps},
core::{FixedTimestep, FixedTimestepState},
prelude::*,
};

const LABEL: &str = "my_fixed_timestep";

#[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(set_fixed_timestep)
// This system will run once every update.
.add_system(frame_update)
// add a new stage that runs twice a second
// This stage will run ten times a 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);
*last_time = time.seconds_since_startup();
fn set_fixed_timestep(mut time: ResMut<FixedTime>) {
time.set_steps_per_second(10.0);
}

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

let fixed_timestep = fixed_timesteps.get(LABEL).unwrap();
fn fixed_update(
mut last_time: Local<f32>,
time: Res<Time>,
fixed_time: Res<FixedTime>,
accumulator: Res<FixedTimestepState>,
) {
info!(
" overstep_percentage: {}",
fixed_timestep.overstep_percentage()
"time since last fixed_update: {}\n",
time.seconds_since_startup() - *last_time
);
info!("fixed timestep: {}\n", fixed_time.delta_seconds());
info!(
"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();
}
19 changes: 14 additions & 5 deletions examples/ecs/iter_combinations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rand::{thread_rng, Rng};
#[derive(Debug, Hash, PartialEq, Eq, Clone, StageLabel)]
struct FixedUpdateStage;

const DELTA_TIME: f64 = 0.01;
const TIME_STEP: f32 = 0.01;

fn main() {
App::new()
Expand All @@ -14,12 +14,13 @@ fn main() {
brightness: 0.03,
..default()
})
.add_startup_system(setup_fixed_timestep)
.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 @@ -49,8 +50,13 @@ struct BodyBundle {
acceleration: Acceleration,
}

fn setup_fixed_timestep(mut time: ResMut<FixedTime>) {
time.set_delta_seconds(TIME_STEP);
}

fn generate_bodies(
mut commands: Commands,
time: Res<FixedTime>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
Expand Down Expand Up @@ -102,7 +108,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,
) * time.delta_seconds(),
),
});
}
Expand Down Expand Up @@ -161,8 +167,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(
time: Res<FixedTime>,
mut query: Query<(&mut Acceleration, &mut Transform, &mut LastPos)>,
) {
let dt_sq = time.delta_seconds() * time.delta_seconds();
for (mut acceleration, mut transform, mut last_pos) in query.iter_mut() {
// verlet integration
// x(t+dt) = 2x(t) - x(t-dt) + a(t)dt^2 + O(dt^4)
Expand Down
9 changes: 7 additions & 2 deletions examples/game/alien_cake_addict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ fn main() {
.init_resource::<Game>()
.add_plugins(DefaultPlugins)
.add_state(GameState::Playing)
.add_startup_system(setup_fixed_timestep)
.add_startup_system(setup_cameras)
.add_system_set(SystemSet::on_enter(GameState::Playing).with_system(setup))
.add_system_set(
Expand All @@ -28,7 +29,7 @@ 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(FixedTimestep::step)
.with_system(spawn_bonus),
)
.add_system(bevy::input::system::exit_on_esc_system)
Expand Down Expand Up @@ -75,6 +76,10 @@ const RESET_FOCUS: [f32; 3] = [
BOARD_SIZE_J as f32 / 2.0 - 0.5,
];

fn setup_fixed_timestep(mut time: ResMut<FixedTime>) {
time.set_delta_seconds(5.0);
}

fn setup_cameras(mut commands: Commands, mut game: ResMut<Game>) {
game.camera_should_focus = Vec3::from(RESET_FOCUS);
game.camera_is_focus = game.camera_should_focus;
Expand Down Expand Up @@ -350,7 +355,7 @@ fn rotate_bonus(game: Res<Game>, time: Res<Time>, mut transforms: Query<&mut Tra
if let Ok(mut cake_transform) = transforms.get_mut(entity) {
cake_transform.rotate(Quat::from_rotation_y(time.delta_seconds()));
cake_transform.scale = Vec3::splat(
1.0 + (game.score as f32 / 10.0 * time.seconds_since_startup().sin() as f32).abs(),
1.0 + (game.score as f32 / 10.0 * time.seconds_since_startup().sin()).abs(),
);
}
}
Expand Down
Loading

0 comments on commit 1441afd

Please sign in to comment.