Skip to content

Commit 4576063

Browse files
Jondolfpull[bot]
authored andcommitted
Add Direction2d::from_xy and Direction3d::from_xyz (#10882)
# Objective Make direction construction a bit more ergonomic. ## Solution Add `Direction2d::from_xy` and `Direction3d::from_xyz`, similar to `Transform::from_xyz`: ```rust let dir2 = Direction2d::from_xy(0.5, 0.5).unwrap(); let dir3 = Direction3d::from_xyz(0.5, 0.5, 0.5).unwrap(); ``` This can be a bit cleaner than using `new`: ```rust let dir2 = Direction2d::new(Vec2::new(0.5, 0.5)).unwrap(); let dir3 = Direction3d::new(Vec3::new(0.5, 0.5, 0.5)).unwrap(); ```
1 parent 6d124db commit 4576063

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

crates/bevy_math/src/primitives/dim2.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,15 @@ impl Direction2d {
2828
)
2929
}
3030

31-
/// Create a direction from a [`Vec2`] that is already normalized
31+
/// Create a direction from its `x` and `y` components.
32+
///
33+
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
34+
/// of the vector formed by the components is zero (or very close to zero), infinite, or `NaN`.
35+
pub fn from_xy(x: f32, y: f32) -> Result<Self, InvalidDirectionError> {
36+
Self::new(Vec2::new(x, y))
37+
}
38+
39+
/// Create a direction from a [`Vec2`] that is already normalized.
3240
pub fn from_normalized(value: Vec2) -> Self {
3341
debug_assert!(value.is_normalized());
3442
Self(value)

crates/bevy_math/src/primitives/dim3.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,15 @@ impl Direction3d {
2828
)
2929
}
3030

31-
/// Create a direction from a [`Vec3`] that is already normalized
31+
/// Create a direction from its `x`, `y`, and `z` components.
32+
///
33+
/// Returns [`Err(InvalidDirectionError)`](InvalidDirectionError) if the length
34+
/// of the vector formed by the components is zero (or very close to zero), infinite, or `NaN`.
35+
pub fn from_xyz(x: f32, y: f32, z: f32) -> Result<Self, InvalidDirectionError> {
36+
Self::new(Vec3::new(x, y, z))
37+
}
38+
39+
/// Create a direction from a [`Vec3`] that is already normalized.
3240
pub fn from_normalized(value: Vec3) -> Self {
3341
debug_assert!(value.is_normalized());
3442
Self(value)

0 commit comments

Comments
 (0)