From 6c78c7b4343c706978c9af525bb88b4d05230599 Mon Sep 17 00:00:00 2001 From: Matty Date: Mon, 6 May 2024 16:53:02 -0400 Subject: [PATCH] Refactor align example to use `Dir3` random sampling (#13259) # Objective Since `align` was introduced, it has been reworked to allow the input of `Dir3` instead of `Vec3`, and we also introduced random sampling for points on a sphere and then for `Dir3`. Previously, this example rolled its own random generation, but it doesn't need to any more. ## Solution Refactor the 'align' example to use `Dir3` instead of `Vec3`, using the `bevy_math` API for random directions. --- examples/transforms/align.rs | 27 +++++---------------------- 1 file changed, 5 insertions(+), 22 deletions(-) diff --git a/examples/transforms/align.rs b/examples/transforms/align.rs index f5b152775f050..acfe4a8d814d7 100644 --- a/examples/transforms/align.rs +++ b/examples/transforms/align.rs @@ -5,7 +5,6 @@ use bevy::input::mouse::{MouseButtonInput, MouseMotion}; use bevy::prelude::*; use rand::{Rng, SeedableRng}; use rand_chacha::ChaCha8Rng; -use std::f32::consts::PI; fn main() { App::new() @@ -33,7 +32,7 @@ struct Cube { } #[derive(Component)] -struct RandomAxes(Vec3, Vec3); +struct RandomAxes(Dir3, Dir3); #[derive(Component)] struct Instructions; @@ -80,8 +79,8 @@ fn setup( }); // Initialize random axes - let first = random_direction(&mut seeded_rng); - let second = random_direction(&mut seeded_rng); + let first = seeded_rng.gen(); + let second = seeded_rng.gen(); commands.spawn(RandomAxes(first, second)); // Finally, our cube that is going to rotate @@ -185,8 +184,8 @@ fn handle_keypress( if keyboard.just_pressed(KeyCode::KeyR) { // Randomize the target axes - let first = random_direction(&mut seeded_rng.0); - let second = random_direction(&mut seeded_rng.0); + let first = seeded_rng.0.gen(); + let second = seeded_rng.0.gen(); *random_axes = RandomAxes(first, second); // Stop the cube and set it up to transform from its present orientation to the new one @@ -243,22 +242,6 @@ fn arrow_ends(transform: &Transform, axis: Vec3, length: f32) -> (Vec3, Vec3) { (transform.translation, transform.translation + local_vector) } -fn random_direction(rng: &mut impl Rng) -> Vec3 { - let height = rng.gen::() * 2. - 1.; - let theta = rng.gen::() * 2. * PI; - - build_direction(height, theta) -} - -fn build_direction(height: f32, theta: f32) -> Vec3 { - let z = height; - let m = f32::acos(z).sin(); - let x = theta.cos() * m; - let y = theta.sin() * m; - - Vec3::new(x, y, z) -} - // This is where `Transform::align` is actually used! // Note that the choice of `Vec3::X` and `Vec3::Y` here matches the use of those in `draw_cube_axes`. fn random_axes_target_alignment(random_axes: &RandomAxes) -> Transform {