bevy/examples/ecs/component_change_detection.rs
Cameron 7989cb2650 Add global time scaling (#5752)
# Objective

- Make `Time` API more consistent.
- Support time accel/decel/pause.

## Solution

This is just the `Time` half of #3002. I was told that part isn't controversial.

- Give the "delta time" and "total elapsed time" methods `f32`, `f64`, and `Duration` variants with consistent naming.
- Implement accelerating / decelerating the passage of time.
- Implement stopping time.

---

## Changelog

- Changed `time_since_startup` to `elapsed` because `time.time_*` is just silly.
- Added `relative_speed` and `set_relative_speed` methods.
- Added `is_paused`, `pause`, `unpause` , and methods. (I'd prefer `resume`, but `unpause` matches `Timer` API.)
- Added `raw_*` variants of the "delta time" and "total elapsed time" methods.
- Added `first_update` method because there's a non-zero duration between startup and the first update.

## Migration Guide

- `time.time_since_startup()` -> `time.elapsed()`
- `time.seconds_since_startup()` -> `time.elapsed_seconds_f64()`
- `time.seconds_since_startup_wrapped_f32()` -> `time.elapsed_seconds_wrapped()`

If you aren't sure which to use, most systems should continue to use "scaled" time (e.g. `time.delta_seconds()`). The realtime "unscaled" time measurements (e.g. `time.raw_delta_seconds()`) are mostly for debugging and profiling.
2022-10-22 18:52:29 +00:00

52 lines
1.4 KiB
Rust

//! This example illustrates how to react to component change.
use bevy::prelude::*;
use rand::Rng;
fn main() {
App::new()
.add_plugins(DefaultPlugins)
.add_startup_system(setup)
.add_system(change_component)
.add_system(change_detection)
.add_system(tracker_monitoring)
.run();
}
#[derive(Component, Debug)]
struct MyComponent(f32);
fn setup(mut commands: Commands) {
commands.spawn(MyComponent(0.));
commands.spawn(Transform::IDENTITY);
}
fn change_component(time: Res<Time>, mut query: Query<(Entity, &mut MyComponent)>) {
for (entity, mut component) in &mut query {
if rand::thread_rng().gen_bool(0.1) {
info!("changing component {:?}", entity);
component.0 = time.elapsed_seconds();
}
}
}
// There are query filters for `Changed<T>` and `Added<T>`
// Only entities matching the filters will be in the query
fn change_detection(query: Query<(Entity, &MyComponent), Changed<MyComponent>>) {
for (entity, component) in &query {
info!("{:?} changed: {:?}", entity, component,);
}
}
// By looking at trackers, the query is not filtered but the information is available
fn tracker_monitoring(
query: Query<(
Entity,
Option<&MyComponent>,
Option<ChangeTrackers<MyComponent>>,
)>,
) {
for (entity, component, trackers) in &query {
info!("{:?}: {:?} -> {:?}", entity, component, trackers);
}
}