Skip to content

Commit 6c78c7b

Browse files
authored
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.
1 parent 60a73fa commit 6c78c7b

File tree

1 file changed

+5
-22
lines changed

1 file changed

+5
-22
lines changed

examples/transforms/align.rs

Lines changed: 5 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use bevy::input::mouse::{MouseButtonInput, MouseMotion};
55
use bevy::prelude::*;
66
use rand::{Rng, SeedableRng};
77
use rand_chacha::ChaCha8Rng;
8-
use std::f32::consts::PI;
98

109
fn main() {
1110
App::new()
@@ -33,7 +32,7 @@ struct Cube {
3332
}
3433

3534
#[derive(Component)]
36-
struct RandomAxes(Vec3, Vec3);
35+
struct RandomAxes(Dir3, Dir3);
3736

3837
#[derive(Component)]
3938
struct Instructions;
@@ -80,8 +79,8 @@ fn setup(
8079
});
8180

8281
// Initialize random axes
83-
let first = random_direction(&mut seeded_rng);
84-
let second = random_direction(&mut seeded_rng);
82+
let first = seeded_rng.gen();
83+
let second = seeded_rng.gen();
8584
commands.spawn(RandomAxes(first, second));
8685

8786
// Finally, our cube that is going to rotate
@@ -185,8 +184,8 @@ fn handle_keypress(
185184

186185
if keyboard.just_pressed(KeyCode::KeyR) {
187186
// Randomize the target axes
188-
let first = random_direction(&mut seeded_rng.0);
189-
let second = random_direction(&mut seeded_rng.0);
187+
let first = seeded_rng.0.gen();
188+
let second = seeded_rng.0.gen();
190189
*random_axes = RandomAxes(first, second);
191190

192191
// 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) {
243242
(transform.translation, transform.translation + local_vector)
244243
}
245244

246-
fn random_direction(rng: &mut impl Rng) -> Vec3 {
247-
let height = rng.gen::<f32>() * 2. - 1.;
248-
let theta = rng.gen::<f32>() * 2. * PI;
249-
250-
build_direction(height, theta)
251-
}
252-
253-
fn build_direction(height: f32, theta: f32) -> Vec3 {
254-
let z = height;
255-
let m = f32::acos(z).sin();
256-
let x = theta.cos() * m;
257-
let y = theta.sin() * m;
258-
259-
Vec3::new(x, y, z)
260-
}
261-
262245
// This is where `Transform::align` is actually used!
263246
// Note that the choice of `Vec3::X` and `Vec3::Y` here matches the use of those in `draw_cube_axes`.
264247
fn random_axes_target_alignment(random_axes: &RandomAxes) -> Transform {

0 commit comments

Comments
 (0)