Skip to content

Commit

Permalink
Refactor align example to use Dir3 random sampling (bevyengine#13259)
Browse files Browse the repository at this point in the history
# 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.
  • Loading branch information
mweatherley committed May 6, 2024
1 parent 60a73fa commit 6c78c7b
Showing 1 changed file with 5 additions and 22 deletions.
27 changes: 5 additions & 22 deletions examples/transforms/align.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -33,7 +32,7 @@ struct Cube {
}

#[derive(Component)]
struct RandomAxes(Vec3, Vec3);
struct RandomAxes(Dir3, Dir3);

#[derive(Component)]
struct Instructions;
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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::<f32>() * 2. - 1.;
let theta = rng.gen::<f32>() * 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 {
Expand Down

0 comments on commit 6c78c7b

Please sign in to comment.