Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove Deref to XYZ from Vec3 #252

Closed
alice-i-cecile opened this issue Oct 27, 2021 · 2 comments
Closed

Remove Deref to XYZ from Vec3 #252

alice-i-cecile opened this issue Oct 27, 2021 · 2 comments

Comments

@alice-i-cecile
Copy link

Bevy users routinely report confusing, frustrating errors with terrible compiler messages when attempting to do basic operations on transforms.

For example, this code fails:

#[derive(Component)]
pub struct Position(Vec3);

pub fn player_controls(
    keyboard_input: Res<Input<KeyCode>>,
    mut query: Query<(&Player, &mut Position)>
) {
    let (player, mut position) = query.single_mut();
    let mut velocity = Vec3::ZERO;
    if keyboard_input.pressed(KeyCode::W) {
        velocity.x += 1.;
    }
    if keyboard_input.pressed(KeyCode::S) {
        velocity.x -= 1.;
    }
    if keyboard_input.pressed(KeyCode::D) {
        velocity.y += 1.;
    }
    if keyboard_input.pressed(KeyCode::A) {
        velocity.y -= 1.;
    }
    *position.0 = *position.0 + velocity.normalize();
}

With the following error message:

error[E0369]: cannot add `bevy::prelude::Vec3` to `bevy::math::XYZ<f32>`
  --> src/player.rs:41:31
   |
41 |     *position.0 = *position.0 + velocity.normalize();
   |                   ----------- ^ -------------------- bevy::prelude::Vec3
   |                   |
   |                   bevy::math::XYZ<f32>

This can be solved by removing the * dereferences from that line.

Tracing the root of this problem, we encounter a Deref and DerefMut implementation of Vec3 to XYZ.

By changing this conversion to be explicit, rather than (mis)using Deref, we can dramatically improve the user experience and error messages.

@bitshifter
Copy link
Owner

Going to close this as addressing it will require rewriting glam internals which is covered by #177. Note that types backed by SIMD such as Vec3A, Vec4, Quat and Mat2 would still require Deref so it will never completely go away but Vec3 and Vec2 could avoid it if code generation is changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants