Consistently use PI to specify angles in examples. (#5825)

Examples inconsistently use either `TAU`, `PI`, `FRAC_PI_2` or `FRAC_PI_4`.
Often in odd ways and without `use`ing the constants, making it difficult to parse.

 * Use `PI` to specify angles.
 * General code-quality improvements.
 * Fix borked `hierarchy` example.


Co-authored-by: devil-ira <justthecooldude@gmail.com>
This commit is contained in:
ira 2022-08-30 19:52:11 +00:00
parent fe6246dac6
commit 65252bb87a
24 changed files with 140 additions and 171 deletions

View File

@ -3,6 +3,8 @@
//! It doesn't use the [`Material2d`] abstraction, but changes the vertex buffer to include vertex color. //! It doesn't use the [`Material2d`] abstraction, but changes the vertex buffer to include vertex color.
//! Check out the "mesh2d" example for simpler / higher level 2d meshes. //! Check out the "mesh2d" example for simpler / higher level 2d meshes.
use std::f32::consts::PI;
use bevy::{ use bevy::{
core_pipeline::core_2d::Transparent2d, core_pipeline::core_2d::Transparent2d,
prelude::*, prelude::*,
@ -62,12 +64,12 @@ fn star(
// These vertices are specified in 3D space. // These vertices are specified in 3D space.
let mut v_pos = vec![[0.0, 0.0, 0.0]]; let mut v_pos = vec![[0.0, 0.0, 0.0]];
for i in 0..10 { for i in 0..10 {
// Angle of each vertex is 1/10 of TAU, plus PI/2 for positioning vertex 0 // The angle between each vertex is 1/10 of a full rotation.
let a = std::f32::consts::FRAC_PI_2 - i as f32 * std::f32::consts::TAU / 10.0; let a = i as f32 * PI / 5.0;
// Radius of internal vertices (2, 4, 6, 8, 10) is 100, it's 200 for external // The radius of inner vertices (even indices) is 100. For outer vertices (odd indices) it's 200.
let r = (1 - i % 2) as f32 * 100.0 + 100.0; let r = (1 - i % 2) as f32 * 100.0 + 100.0;
// Add the vertex coordinates // Add the vertex position.
v_pos.push([r * a.cos(), r * a.sin(), 0.0]); v_pos.push([r * a.sin(), r * a.cos(), 0.0]);
} }
// Set the position attribute // Set the position attribute
star.insert_attribute(Mesh::ATTRIBUTE_POSITION, v_pos); star.insert_attribute(Mesh::ATTRIBUTE_POSITION, v_pos);

View File

@ -1,6 +1,8 @@
//! Illustrates different lights of various types and colors, some static, some moving over //! Illustrates different lights of various types and colors, some static, some moving over
//! a simple scene. //! a simple scene.
use std::f32::consts::PI;
use bevy::prelude::*; use bevy::prelude::*;
fn main() { fn main() {
@ -34,7 +36,7 @@ fn setup(
// left wall // left wall
let mut transform = Transform::from_xyz(2.5, 2.5, 0.0); let mut transform = Transform::from_xyz(2.5, 2.5, 0.0);
transform.rotate_z(std::f32::consts::FRAC_PI_2); transform.rotate_z(PI / 2.);
commands.spawn_bundle(PbrBundle { commands.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Box::new(5.0, 0.15, 5.0))), mesh: meshes.add(Mesh::from(shape::Box::new(5.0, 0.15, 5.0))),
transform, transform,
@ -47,7 +49,7 @@ fn setup(
}); });
// back (right) wall // back (right) wall
let mut transform = Transform::from_xyz(0.0, 2.5, -2.5); let mut transform = Transform::from_xyz(0.0, 2.5, -2.5);
transform.rotate_x(std::f32::consts::FRAC_PI_2); transform.rotate_x(PI / 2.);
commands.spawn_bundle(PbrBundle { commands.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Box::new(5.0, 0.15, 5.0))), mesh: meshes.add(Mesh::from(shape::Box::new(5.0, 0.15, 5.0))),
transform, transform,
@ -138,9 +140,7 @@ fn setup(
}) })
.with_children(|builder| { .with_children(|builder| {
builder.spawn_bundle(PbrBundle { builder.spawn_bundle(PbrBundle {
transform: Transform::from_rotation(Quat::from_rotation_x( transform: Transform::from_rotation(Quat::from_rotation_x(PI / 2.0)),
std::f32::consts::PI / 2.0,
)),
mesh: meshes.add(Mesh::from(shape::Capsule { mesh: meshes.add(Mesh::from(shape::Capsule {
depth: 0.125, depth: 0.125,
radius: 0.1, radius: 0.1,
@ -202,7 +202,7 @@ fn setup(
}, },
transform: Transform { transform: Transform {
translation: Vec3::new(0.0, 2.0, 0.0), translation: Vec3::new(0.0, 2.0, 0.0),
rotation: Quat::from_rotation_x(-std::f32::consts::FRAC_PI_4), rotation: Quat::from_rotation_x(-PI / 4.),
..default() ..default()
}, },
..default() ..default()

View File

@ -1,5 +1,7 @@
//! Loads and renders a glTF file as a scene. //! Loads and renders a glTF file as a scene.
use std::f32::consts::PI;
use bevy::prelude::*; use bevy::prelude::*;
fn main() { fn main() {
@ -50,8 +52,8 @@ fn animate_light_direction(
transform.rotation = Quat::from_euler( transform.rotation = Quat::from_euler(
EulerRot::ZYX, EulerRot::ZYX,
0.0, 0.0,
time.seconds_since_startup() as f32 * std::f32::consts::TAU / 10.0, time.seconds_since_startup() as f32 * PI / 5.0,
-std::f32::consts::FRAC_PI_4, -PI / 4.,
); );
} }
} }

View File

@ -1,5 +1,7 @@
//! Shows how to render to a texture. Useful for mirrors, UI, or exporting images. //! Shows how to render to a texture. Useful for mirrors, UI, or exporting images.
use std::f32::consts::PI;
use bevy::{ use bevy::{
core_pipeline::clear_color::ClearColorConfig, core_pipeline::clear_color::ClearColorConfig,
prelude::*, prelude::*,
@ -104,7 +106,7 @@ fn setup(
..default() ..default()
}, },
transform: Transform::from_translation(Vec3::new(0.0, 0.0, 15.0)) transform: Transform::from_translation(Vec3::new(0.0, 0.0, 15.0))
.looking_at(Vec3::default(), Vec3::Y), .looking_at(Vec3::ZERO, Vec3::Y),
..default() ..default()
}) })
.insert(first_pass_layer); .insert(first_pass_layer);
@ -125,19 +127,15 @@ fn setup(
.spawn_bundle(PbrBundle { .spawn_bundle(PbrBundle {
mesh: cube_handle, mesh: cube_handle,
material: material_handle, material: material_handle,
transform: Transform { transform: Transform::from_xyz(0.0, 0.0, 1.5)
translation: Vec3::new(0.0, 0.0, 1.5), .with_rotation(Quat::from_rotation_x(-PI / 5.0)),
rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),
..default()
},
..default() ..default()
}) })
.insert(MainPassCube); .insert(MainPassCube);
// The main pass camera. // The main pass camera.
commands.spawn_bundle(Camera3dBundle { commands.spawn_bundle(Camera3dBundle {
transform: Transform::from_translation(Vec3::new(0.0, 0.0, 15.0)) transform: Transform::from_xyz(0.0, 0.0, 15.0).looking_at(Vec3::ZERO, Vec3::Y),
.looking_at(Vec3::default(), Vec3::Y),
..default() ..default()
}); });
} }

View File

@ -1,5 +1,7 @@
//! Demonstrates how shadow biases affect shadows in a 3d scene. //! Demonstrates how shadow biases affect shadows in a 3d scene.
use std::f32::consts::PI;
use bevy::{input::mouse::MouseMotion, prelude::*}; use bevy::{input::mouse::MouseMotion, prelude::*};
fn main() { fn main() {
@ -61,8 +63,6 @@ fn setup(
..default() ..default()
}); });
let theta = std::f32::consts::FRAC_PI_4;
let light_transform = Mat4::from_euler(EulerRot::ZYX, 0.0, std::f32::consts::FRAC_PI_2, -theta);
commands.spawn_bundle(DirectionalLightBundle { commands.spawn_bundle(DirectionalLightBundle {
directional_light: DirectionalLight { directional_light: DirectionalLight {
illuminance: 100000.0, illuminance: 100000.0,
@ -80,7 +80,12 @@ fn setup(
shadows_enabled: true, shadows_enabled: true,
..default() ..default()
}, },
transform: Transform::from_matrix(light_transform), transform: Transform::from_rotation(Quat::from_euler(
EulerRot::ZYX,
0.0,
PI / 2.,
-PI / 4.,
)),
..default() ..default()
}); });
@ -308,16 +313,10 @@ fn camera_controller(
if mouse_delta != Vec2::ZERO { if mouse_delta != Vec2::ZERO {
// Apply look update // Apply look update
let (pitch, yaw) = ( options.pitch = (options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt)
(options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt).clamp( .clamp(-PI / 2., PI / 2.);
-0.99 * std::f32::consts::FRAC_PI_2, options.yaw -= mouse_delta.x * options.sensitivity * dt;
0.99 * std::f32::consts::FRAC_PI_2, transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, options.yaw, options.pitch);
),
options.yaw - mouse_delta.x * options.sensitivity * dt,
);
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, yaw, pitch);
options.pitch = pitch;
options.yaw = yaw;
} }
} }
} }

View File

@ -1,5 +1,7 @@
//! Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene. //! Demonstrates how to prevent meshes from casting/receiving shadows in a 3d scene.
use std::f32::consts::PI;
use bevy::{ use bevy::{
pbr::{NotShadowCaster, NotShadowReceiver}, pbr::{NotShadowCaster, NotShadowReceiver},
prelude::*, prelude::*,
@ -89,8 +91,6 @@ fn setup(
..default() ..default()
}); });
let theta = std::f32::consts::FRAC_PI_4;
let light_transform = Mat4::from_euler(EulerRot::ZYX, 0.0, std::f32::consts::FRAC_PI_2, -theta);
commands.spawn_bundle(DirectionalLightBundle { commands.spawn_bundle(DirectionalLightBundle {
directional_light: DirectionalLight { directional_light: DirectionalLight {
illuminance: 100000.0, illuminance: 100000.0,
@ -106,7 +106,12 @@ fn setup(
shadows_enabled: true, shadows_enabled: true,
..default() ..default()
}, },
transform: Transform::from_matrix(light_transform), transform: Transform::from_rotation(Quat::from_euler(
EulerRot::ZYX,
0.0,
PI / 2.,
-PI / 4.,
)),
..default() ..default()
}); });

View File

@ -1,6 +1,8 @@
//! This example demonstrates the built-in 3d shapes in Bevy. //! This example demonstrates the built-in 3d shapes in Bevy.
//! The scene includes a patterned texture and a rotation for visualizing the normals and UVs. //! The scene includes a patterned texture and a rotation for visualizing the normals and UVs.
use std::f32::consts::PI;
use bevy::{ use bevy::{
prelude::*, prelude::*,
render::render_resource::{Extent3d, TextureDimension, TextureFormat}, render::render_resource::{Extent3d, TextureDimension, TextureFormat},
@ -48,15 +50,12 @@ fn setup(
.spawn_bundle(PbrBundle { .spawn_bundle(PbrBundle {
mesh: shape, mesh: shape,
material: debug_material.clone(), material: debug_material.clone(),
transform: Transform { transform: Transform::from_xyz(
translation: Vec3::new( -X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT,
-X_EXTENT / 2. + i as f32 / (num_shapes - 1) as f32 * X_EXTENT, 2.0,
2.0, 0.0,
0.0, )
), .with_rotation(Quat::from_rotation_x(-PI / 4.)),
rotation: Quat::from_rotation_x(-std::f32::consts::PI / 4.),
..default()
},
..default() ..default()
}) })
.insert(Shape); .insert(Shape);

View File

@ -1,5 +1,7 @@
//! Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats //! Load a cubemap texture onto a cube like a skybox and cycle through different compressed texture formats
use std::f32::consts::PI;
use bevy::{ use bevy::{
asset::LoadState, asset::LoadState,
input::mouse::MouseMotion, input::mouse::MouseMotion,
@ -66,11 +68,8 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
illuminance: 32000.0, illuminance: 32000.0,
..default() ..default()
}, },
transform: Transform { transform: Transform::from_xyz(0.0, 2.0, 0.0)
translation: Vec3::new(0.0, 2.0, 0.0), .with_rotation(Quat::from_rotation_x(-PI / 4.)),
rotation: Quat::from_rotation_x(-std::f32::consts::FRAC_PI_4),
..default()
},
..default() ..default()
}); });
@ -78,7 +77,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// camera // camera
commands commands
.spawn_bundle(Camera3dBundle { .spawn_bundle(Camera3dBundle {
transform: Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::default(), Vec3::Y), transform: Transform::from_xyz(0.0, 0.0, 8.0).looking_at(Vec3::ZERO, Vec3::Y),
..default() ..default()
}) })
.insert(CameraController::default()); .insert(CameraController::default());
@ -410,16 +409,10 @@ pub fn camera_controller(
if mouse_delta != Vec2::ZERO { if mouse_delta != Vec2::ZERO {
// Apply look update // Apply look update
let (pitch, yaw) = ( options.pitch = (options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt)
(options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt).clamp( .clamp(-PI / 2., PI / 2.);
-0.99 * std::f32::consts::FRAC_PI_2, options.yaw -= mouse_delta.x * options.sensitivity * dt;
0.99 * std::f32::consts::FRAC_PI_2, transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, options.yaw, options.pitch);
),
options.yaw - mouse_delta.x * options.sensitivity * dt,
);
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, yaw, pitch);
options.pitch = pitch;
options.yaw = yaw;
} }
} }
} }

View File

@ -1,5 +1,7 @@
//! Renders two cameras to the same window to accomplish "split screen". //! Renders two cameras to the same window to accomplish "split screen".
use std::f32::consts::PI;
use bevy::{ use bevy::{
core_pipeline::clear_color::ClearColorConfig, core_pipeline::clear_color::ClearColorConfig,
prelude::*, prelude::*,
@ -36,12 +38,7 @@ fn setup(
// Light // Light
commands.spawn_bundle(DirectionalLightBundle { commands.spawn_bundle(DirectionalLightBundle {
transform: Transform::from_rotation(Quat::from_euler( transform: Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
EulerRot::ZYX,
0.0,
1.0,
-std::f32::consts::FRAC_PI_4,
)),
directional_light: DirectionalLight { directional_light: DirectionalLight {
shadows_enabled: true, shadows_enabled: true,
..default() ..default()

View File

@ -1,3 +1,5 @@
use std::f32::consts::PI;
use bevy::{ use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
pbr::NotShadowCaster, pbr::NotShadowCaster,
@ -74,8 +76,8 @@ fn setup(
intensity: 200.0, // lumens intensity: 200.0, // lumens
color: Color::WHITE, color: Color::WHITE,
shadows_enabled: true, shadows_enabled: true,
inner_angle: std::f32::consts::PI / 4.0 * 0.85, inner_angle: PI / 4.0 * 0.85,
outer_angle: std::f32::consts::PI / 4.0, outer_angle: PI / 4.0,
..default() ..default()
}, },
..default() ..default()
@ -123,13 +125,11 @@ fn light_sway(time: Res<Time>, mut query: Query<(&mut Transform, &mut SpotLight)
for (mut transform, mut angles) in query.iter_mut() { for (mut transform, mut angles) in query.iter_mut() {
transform.rotation = Quat::from_euler( transform.rotation = Quat::from_euler(
EulerRot::XYZ, EulerRot::XYZ,
-std::f32::consts::FRAC_PI_2 -PI / 2. + (time.seconds_since_startup() * 0.67 * 3.0).sin() as f32 * 0.5,
+ (time.seconds_since_startup() * 0.67 * 3.0).sin() as f32 * 0.5,
(time.seconds_since_startup() * 3.0).sin() as f32 * 0.5, (time.seconds_since_startup() * 3.0).sin() as f32 * 0.5,
0.0, 0.0,
); );
let angle = ((time.seconds_since_startup() * 1.2).sin() as f32 + 1.0) let angle = ((time.seconds_since_startup() * 1.2).sin() as f32 + 1.0) * (PI / 4. - 0.1);
* (std::f32::consts::FRAC_PI_4 - 0.1);
angles.inner_angle = angle * 0.8; angles.inner_angle = angle * 0.8;
angles.outer_angle = angle; angles.outer_angle = angle;
} }
@ -140,7 +140,7 @@ fn movement(
time: Res<Time>, time: Res<Time>,
mut query: Query<&mut Transform, With<Movable>>, mut query: Query<&mut Transform, With<Movable>>,
) { ) {
for mut transform in query.iter_mut() { for mut transform in &mut query {
let mut direction = Vec3::ZERO; let mut direction = Vec3::ZERO;
if input.pressed(KeyCode::Up) { if input.pressed(KeyCode::Up) {
direction.z -= 1.0; direction.z -= 1.0;

View File

@ -1,5 +1,7 @@
//! This example shows various ways to configure texture materials in 3D. //! This example shows various ways to configure texture materials in 3D.
use std::f32::consts::PI;
use bevy::prelude::*; use bevy::prelude::*;
fn main() { fn main() {
@ -57,33 +59,23 @@ fn setup(
commands.spawn_bundle(PbrBundle { commands.spawn_bundle(PbrBundle {
mesh: quad_handle.clone(), mesh: quad_handle.clone(),
material: material_handle, material: material_handle,
transform: Transform { transform: Transform::from_xyz(0.0, 0.0, 1.5)
translation: Vec3::new(0.0, 0.0, 1.5), .with_rotation(Quat::from_rotation_x(-PI / 5.0)),
rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),
..default()
},
..default() ..default()
}); });
// textured quad - modulated // textured quad - modulated
commands.spawn_bundle(PbrBundle { commands.spawn_bundle(PbrBundle {
mesh: quad_handle.clone(), mesh: quad_handle.clone(),
material: red_material_handle, material: red_material_handle,
transform: Transform { transform: Transform::from_rotation(Quat::from_rotation_x(-PI / 5.0)),
translation: Vec3::new(0.0, 0.0, 0.0),
rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),
..default()
},
..default() ..default()
}); });
// textured quad - modulated // textured quad - modulated
commands.spawn_bundle(PbrBundle { commands.spawn_bundle(PbrBundle {
mesh: quad_handle, mesh: quad_handle,
material: blue_material_handle, material: blue_material_handle,
transform: Transform { transform: Transform::from_xyz(0.0, 0.0, -1.5)
translation: Vec3::new(0.0, 0.0, -1.5), .with_rotation(Quat::from_rotation_x(-PI / 5.0)),
rotation: Quat::from_rotation_x(-std::f32::consts::PI / 5.0),
..default()
},
..default() ..default()
}); });
// camera // camera

View File

@ -1,5 +1,7 @@
//! Plays animations from a skinned glTF. //! Plays animations from a skinned glTF.
use std::f32::consts::PI;
use bevy::prelude::*; use bevy::prelude::*;
fn main() { fn main() {
@ -47,12 +49,7 @@ fn setup(
// Light // Light
commands.spawn_bundle(DirectionalLightBundle { commands.spawn_bundle(DirectionalLightBundle {
transform: Transform::from_rotation(Quat::from_euler( transform: Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
EulerRot::ZYX,
0.0,
1.0,
-std::f32::consts::FRAC_PI_4,
)),
directional_light: DirectionalLight { directional_light: DirectionalLight {
shadows_enabled: true, shadows_enabled: true,
..default() ..default()

View File

@ -1,6 +1,6 @@
//! Create and play an animation defined by code that operates on the `Transform` component. //! Create and play an animation defined by code that operates on the `Transform` component.
use std::f32::consts::{FRAC_PI_2, PI}; use std::f32::consts::PI;
use bevy::prelude::*; use bevy::prelude::*;
@ -62,11 +62,11 @@ fn setup(
VariableCurve { VariableCurve {
keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0], keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0],
keyframes: Keyframes::Rotation(vec![ keyframes: Keyframes::Rotation(vec![
Quat::from_axis_angle(Vec3::Y, 0.0), Quat::IDENTITY,
Quat::from_axis_angle(Vec3::Y, FRAC_PI_2), Quat::from_axis_angle(Vec3::Y, PI / 2.),
Quat::from_axis_angle(Vec3::Y, PI), Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
Quat::from_axis_angle(Vec3::Y, 3.0 * FRAC_PI_2), Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
Quat::from_axis_angle(Vec3::Y, 0.0), Quat::IDENTITY,
]), ]),
}, },
); );
@ -100,11 +100,11 @@ fn setup(
VariableCurve { VariableCurve {
keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0], keyframe_timestamps: vec![0.0, 1.0, 2.0, 3.0, 4.0],
keyframes: Keyframes::Rotation(vec![ keyframes: Keyframes::Rotation(vec![
Quat::from_axis_angle(Vec3::Y, 0.0), Quat::IDENTITY,
Quat::from_axis_angle(Vec3::Y, FRAC_PI_2), Quat::from_axis_angle(Vec3::Y, PI / 2.),
Quat::from_axis_angle(Vec3::Y, PI), Quat::from_axis_angle(Vec3::Y, PI / 2. * 2.),
Quat::from_axis_angle(Vec3::Y, 3.0 * FRAC_PI_2), Quat::from_axis_angle(Vec3::Y, PI / 2. * 3.),
Quat::from_axis_angle(Vec3::Y, 0.0), Quat::IDENTITY,
]), ]),
}, },
); );

View File

@ -164,9 +164,7 @@ fn setup(
/// Animate the joint marked with [`AnimatedJoint`] component. /// Animate the joint marked with [`AnimatedJoint`] component.
fn joint_animation(time: Res<Time>, mut query: Query<&mut Transform, With<AnimatedJoint>>) { fn joint_animation(time: Res<Time>, mut query: Query<&mut Transform, With<AnimatedJoint>>) {
for mut transform in &mut query { for mut transform in &mut query {
transform.rotation = Quat::from_axis_angle( transform.rotation =
Vec3::Z, Quat::from_rotation_z(PI / 2. * time.time_since_startup().as_secs_f32().sin());
0.5 * PI * time.time_since_startup().as_secs_f32().sin(),
);
} }
} }

View File

@ -66,9 +66,7 @@ fn joint_animation(
// Get `Transform` in the second joint. // Get `Transform` in the second joint.
let mut second_joint_transform = transform_query.get_mut(second_joint_entity).unwrap(); let mut second_joint_transform = transform_query.get_mut(second_joint_entity).unwrap();
second_joint_transform.rotation = Quat::from_axis_angle( second_joint_transform.rotation =
Vec3::Z, Quat::from_rotation_z(PI / 2. * time.time_since_startup().as_secs_f32().sin());
0.5 * PI * time.time_since_startup().as_secs_f32().sin(),
);
} }
} }

View File

@ -9,7 +9,7 @@
//! For more advice on working with generic types in Rust, check out <https://doc.rust-lang.org/book/ch10-01-syntax.html> //! For more advice on working with generic types in Rust, check out <https://doc.rust-lang.org/book/ch10-01-syntax.html>
//! or <https://doc.rust-lang.org/rust-by-example/generics.html> //! or <https://doc.rust-lang.org/rust-by-example/generics.html>
use bevy::{ecs::component::Component, prelude::*}; use bevy::prelude::*;
#[derive(Debug, Clone, Eq, PartialEq, Hash)] #[derive(Debug, Clone, Eq, PartialEq, Hash)]
enum AppState { enum AppState {
@ -21,7 +21,7 @@ enum AppState {
struct TextToPrint(String); struct TextToPrint(String);
#[derive(Component, Deref, DerefMut)] #[derive(Component, Deref, DerefMut)]
struct PrinterTick(bevy::prelude::Timer); struct PrinterTick(Timer);
#[derive(Component)] #[derive(Component)]
struct MenuClose; struct MenuClose;
@ -52,7 +52,7 @@ fn main() {
fn setup_system(mut commands: Commands) { fn setup_system(mut commands: Commands) {
commands commands
.spawn() .spawn()
.insert(PrinterTick(bevy::prelude::Timer::from_seconds(1.0, true))) .insert(PrinterTick(Timer::from_seconds(1.0, true)))
.insert(TextToPrint( .insert(TextToPrint(
"I will print until you press space.".to_string(), "I will print until you press space.".to_string(),
)) ))
@ -60,7 +60,7 @@ fn setup_system(mut commands: Commands) {
commands commands
.spawn() .spawn()
.insert(PrinterTick(bevy::prelude::Timer::from_seconds(1.0, true))) .insert(PrinterTick(Timer::from_seconds(1.0, true)))
.insert(TextToPrint("I will always print".to_string())) .insert(TextToPrint("I will always print".to_string()))
.insert(LevelUnload); .insert(LevelUnload);
} }

View File

@ -1,5 +1,7 @@
//! Creates a hierarchy of parents and children entities. //! Creates a hierarchy of parents and children entities.
use std::f32::consts::PI;
use bevy::prelude::*; use bevy::prelude::*;
fn main() { fn main() {
@ -25,11 +27,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
.with_children(|parent| { .with_children(|parent| {
// parent is a ChildBuilder, which has a similar API to Commands // parent is a ChildBuilder, which has a similar API to Commands
parent.spawn_bundle(SpriteBundle { parent.spawn_bundle(SpriteBundle {
transform: Transform { transform: Transform::from_xyz(250.0, 0.0, 0.0).with_scale(Vec3::splat(0.75)),
translation: Vec3::new(250.0, 0.0, 0.0),
scale: Vec3::splat(0.75),
..default()
},
texture: texture.clone(), texture: texture.clone(),
sprite: Sprite { sprite: Sprite {
color: Color::BLUE, color: Color::BLUE,
@ -45,11 +43,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
// entity has already been spawned. // entity has already been spawned.
let child = commands let child = commands
.spawn_bundle(SpriteBundle { .spawn_bundle(SpriteBundle {
transform: Transform { transform: Transform::from_xyz(0.0, 250.0, 0.0).with_scale(Vec3::splat(0.75)),
translation: Vec3::new(0.0, 250.0, 0.0),
scale: Vec3::splat(0.75),
..default()
},
texture, texture,
sprite: Sprite { sprite: Sprite {
color: Color::GREEN, color: Color::GREEN,
@ -59,8 +53,8 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
}) })
.id(); .id();
// Pushing takes a slice of children to add: // Add child to the parent.
commands.entity(parent).push_children(&[child]); commands.entity(parent).add_child(child);
} }
// A simple system to rotate the root entity, and rotate all its children separately // A simple system to rotate the root entity, and rotate all its children separately
@ -70,25 +64,23 @@ fn rotate(
mut parents_query: Query<(Entity, &Children), With<Sprite>>, mut parents_query: Query<(Entity, &Children), With<Sprite>>,
mut transform_query: Query<&mut Transform, With<Sprite>>, mut transform_query: Query<&mut Transform, With<Sprite>>,
) { ) {
let angle = std::f32::consts::PI / 2.0;
for (parent, children) in &mut parents_query { for (parent, children) in &mut parents_query {
if let Ok(mut transform) = transform_query.get_mut(parent) { if let Ok(mut transform) = transform_query.get_mut(parent) {
transform.rotate_z(-angle * time.delta_seconds()); transform.rotate_z(-PI / 2. * time.delta_seconds());
} }
// To iterate through the entities children, just treat the Children component as a Vec // To iterate through the entities children, just treat the Children component as a Vec
// Alternatively, you could query entities that have a Parent component // Alternatively, you could query entities that have a Parent component
for child in children { for child in children {
if let Ok(mut transform) = transform_query.get_mut(*child) { if let Ok(mut transform) = transform_query.get_mut(*child) {
transform.rotate_z(angle * 2.0 * time.delta_seconds()); transform.rotate_z(PI * time.delta_seconds());
} }
} }
// To demonstrate removing children, we'll start to remove the children after a couple of // To demonstrate removing children, we'll remove a child after a couple of seconds.
// seconds if time.seconds_since_startup() >= 2.0 && children.len() == 2 {
if time.seconds_since_startup() >= 2.0 && children.len() == 3 { let child = children.last().unwrap();
let child = children.last().copied().unwrap(); commands.entity(*child).despawn_recursive();
commands.entity(child).despawn_recursive();
} }
if time.seconds_since_startup() >= 4.0 { if time.seconds_since_startup() >= 4.0 {

View File

@ -1,5 +1,7 @@
//! Eat the cakes. Eat them all. An example 3D game. //! Eat the cakes. Eat them all. An example 3D game.
use std::f32::consts::PI;
use bevy::{ecs::schedule::SystemSet, prelude::*, time::FixedTimestep}; use bevy::{ecs::schedule::SystemSet, prelude::*, time::FixedTimestep};
use rand::Rng; use rand::Rng;
@ -137,7 +139,7 @@ fn setup(mut commands: Commands, asset_server: Res<AssetServer>, mut game: ResMu
game.board[game.player.j][game.player.i].height, game.board[game.player.j][game.player.i].height,
game.player.j as f32, game.player.j as f32,
), ),
rotation: Quat::from_rotation_y(-std::f32::consts::FRAC_PI_2), rotation: Quat::from_rotation_y(-PI / 2.),
..default() ..default()
}, },
scene: asset_server.load("models/AlienCake/alien.glb#Scene0"), scene: asset_server.load("models/AlienCake/alien.glb#Scene0"),
@ -194,21 +196,21 @@ fn move_player(
if game.player.i < BOARD_SIZE_I - 1 { if game.player.i < BOARD_SIZE_I - 1 {
game.player.i += 1; game.player.i += 1;
} }
rotation = -std::f32::consts::FRAC_PI_2; rotation = -PI / 2.;
moved = true; moved = true;
} }
if keyboard_input.pressed(KeyCode::Down) { if keyboard_input.pressed(KeyCode::Down) {
if game.player.i > 0 { if game.player.i > 0 {
game.player.i -= 1; game.player.i -= 1;
} }
rotation = std::f32::consts::FRAC_PI_2; rotation = PI / 2.;
moved = true; moved = true;
} }
if keyboard_input.pressed(KeyCode::Right) { if keyboard_input.pressed(KeyCode::Right) {
if game.player.j < BOARD_SIZE_J - 1 { if game.player.j < BOARD_SIZE_J - 1 {
game.player.j += 1; game.player.j += 1;
} }
rotation = std::f32::consts::PI; rotation = PI;
moved = true; moved = true;
} }
if keyboard_input.pressed(KeyCode::Left) { if keyboard_input.pressed(KeyCode::Left) {

View File

@ -10,6 +10,8 @@
//! To start the demo using the spherical layout run //! To start the demo using the spherical layout run
//! `cargo run --example many_cubes --release sphere` //! `cargo run --example many_cubes --release sphere`
use std::f64::consts::PI;
use bevy::{ use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
math::{DVec2, DVec3}, math::{DVec2, DVec3},
@ -142,7 +144,7 @@ const EPSILON: f64 = 0.36;
fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 { fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 {
DVec2::new( DVec2::new(
2.0 * std::f64::consts::PI * (i as f64 / golden_ratio), PI * 2. * (i as f64 / golden_ratio),
(1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)).acos(), (1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)).acos(),
) )
} }

View File

@ -1,6 +1,8 @@
//! Loads animations from a skinned glTF, spawns many of them, and plays the //! Loads animations from a skinned glTF, spawns many of them, and plays the
//! animation to stress test skinned meshes. //! animation to stress test skinned meshes.
use std::f32::consts::PI;
use bevy::{ use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
prelude::*, prelude::*,
@ -93,7 +95,7 @@ fn setup(
let ring_directions = [ let ring_directions = [
( (
Quat::from_rotation_y(std::f32::consts::PI), Quat::from_rotation_y(PI),
RotationDirection::CounterClockwise, RotationDirection::CounterClockwise,
), ),
(Quat::IDENTITY, RotationDirection::Clockwise), (Quat::IDENTITY, RotationDirection::Clockwise),
@ -118,7 +120,7 @@ fn setup(
)) ))
.id(); .id();
let circumference = std::f32::consts::TAU * radius; let circumference = PI * 2. * radius;
let foxes_in_ring = ((circumference / FOX_SPACING) as usize).min(foxes_remaining); let foxes_in_ring = ((circumference / FOX_SPACING) as usize).min(foxes_remaining);
let fox_spacing_angle = circumference / (foxes_in_ring as f32 * radius); let fox_spacing_angle = circumference / (foxes_in_ring as f32 * radius);
@ -165,12 +167,7 @@ fn setup(
// Light // Light
commands.spawn_bundle(DirectionalLightBundle { commands.spawn_bundle(DirectionalLightBundle {
transform: Transform::from_rotation(Quat::from_euler( transform: Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
EulerRot::ZYX,
0.0,
1.0,
-std::f32::consts::FRAC_PI_4,
)),
directional_light: DirectionalLight { directional_light: DirectionalLight {
shadows_enabled: true, shadows_enabled: true,
..default() ..default()

View File

@ -1,6 +1,8 @@
//! Simple benchmark to test rendering many point lights. //! Simple benchmark to test rendering many point lights.
//! Run with `WGPU_SETTINGS_PRIO=webgl2` to restrict to uniform buffers and max 256 lights. //! Run with `WGPU_SETTINGS_PRIO=webgl2` to restrict to uniform buffers and max 256 lights.
use std::f64::consts::PI;
use bevy::{ use bevy::{
diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin}, diagnostic::{FrameTimeDiagnosticsPlugin, LogDiagnosticsPlugin},
math::{DVec2, DVec3}, math::{DVec2, DVec3},
@ -113,7 +115,7 @@ fn setup(
const EPSILON: f64 = 0.36; const EPSILON: f64 = 0.36;
fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 { fn fibonacci_spiral_on_sphere(golden_ratio: f64, i: usize, n: usize) -> DVec2 {
DVec2::new( DVec2::new(
2.0 * std::f64::consts::PI * (i as f64 / golden_ratio), PI * 2. * (i as f64 / golden_ratio),
(1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)).acos(), (1.0 - 2.0 * (i as f64 + EPSILON) / (n as f64 - 1.0 + 2.0 * EPSILON)).acos(),
) )
} }

View File

@ -14,7 +14,7 @@ use bevy::{
scene::InstanceId, scene::InstanceId,
}; };
use std::f32::consts::TAU; use std::f32::consts::PI;
#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel)] #[derive(Debug, Hash, PartialEq, Eq, Clone, SystemLabel)]
struct CameraControllerCheckSystem; struct CameraControllerCheckSystem;
@ -330,8 +330,8 @@ fn update_lights(
transform.rotation = Quat::from_euler( transform.rotation = Quat::from_euler(
EulerRot::ZYX, EulerRot::ZYX,
0.0, 0.0,
time.seconds_since_startup() as f32 * TAU / 30.0, time.seconds_since_startup() as f32 * PI / 15.0,
-TAU / 8., -PI / 4.,
); );
} }
} }
@ -526,16 +526,10 @@ fn camera_controller(
if mouse_delta != Vec2::ZERO { if mouse_delta != Vec2::ZERO {
// Apply look update // Apply look update
let (pitch, yaw) = ( options.pitch = (options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt)
(options.pitch - mouse_delta.y * 0.5 * options.sensitivity * dt).clamp( .clamp(-PI / 2., PI / 2.);
-0.99 * std::f32::consts::FRAC_PI_2, options.yaw -= mouse_delta.x * options.sensitivity * dt;
0.99 * std::f32::consts::FRAC_PI_2, transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, options.yaw, options.pitch);
),
options.yaw - mouse_delta.x * options.sensitivity * dt,
);
transform.rotation = Quat::from_euler(EulerRot::ZYX, 0.0, yaw, pitch);
options.pitch = pitch;
options.yaw = yaw;
} }
} }
} }

View File

@ -1,8 +1,9 @@
//! Illustrates how to scale an object in each direction. //! Illustrates how to scale an object in each direction.
use std::f32::consts::PI;
use bevy::math::Vec3Swizzles; use bevy::math::Vec3Swizzles;
use bevy::prelude::*; use bevy::prelude::*;
use std::f32::consts::PI;
// Define a component to keep information for the scaled object. // Define a component to keep information for the scaled object.
#[derive(Component)] #[derive(Component)]

View File

@ -1,9 +1,9 @@
//! Shows multiple transformations of objects. //! Shows multiple transformations of objects.
use bevy::prelude::*;
use std::f32::consts::PI; use std::f32::consts::PI;
use bevy::prelude::*;
// A struct for additional data of for a moving cube. // A struct for additional data of for a moving cube.
#[derive(Component)] #[derive(Component)]
struct CubeState { struct CubeState {
@ -59,9 +59,8 @@ fn setup(
// by changing its rotation each frame and moving forward. // by changing its rotation each frame and moving forward.
// Define a start transform for an orbiting cube, that's away from our central object (sphere) // Define a start transform for an orbiting cube, that's away from our central object (sphere)
// and rotate it so it will be able to move around the sphere and not towards it. // and rotate it so it will be able to move around the sphere and not towards it.
let angle_90 = PI / 2.0;
let cube_spawn = let cube_spawn =
Transform::from_translation(Vec3::Z * -10.0).with_rotation(Quat::from_rotation_y(angle_90)); Transform::from_translation(Vec3::Z * -10.0).with_rotation(Quat::from_rotation_y(PI / 2.));
commands commands
.spawn_bundle(PbrBundle { .spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })), mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),