#Modify subset of fields (rust newbie)

10 messages · Page 1 of 1 (latest)

bold barn
#

I'm trying to write a system that updates the camera position to that of a target entity's x and y values.

fn update_camera(
    camera_query: Query<(&mut Transform, &CameraTarget)>,
    targets_query: Query<&Transform>,
) {
    let (camera_transform, camera_target) = camera_query.single();
    if let Some(target) = camera_target.target {
        if let Ok(target_transform) = targets_query.get_component::<Transform>(target) {
            // Option 1:
            *camera_transform = Transform {
                translation: Vec3 {
                    x: target_transform.translation.x,
                    y: target_transform.translation.y,
                    ..target_transform.translation
                },
                ..*target_transform
            };
            // Option 2:
            camera_transform.translation.x = target_transform.translation.x;
            camera_transform.translation.y = target_transform.translation.y;
        }
    }
}```

Is this typically how you would do it with bevy's API?

I came up with two ways (option 1 and 2) of copy the x and y values but they both seem quite annoying to write. In other languages It could have been handled by a getter and setter like so:

``camera_transform.translation.xy = target_transform.translation.xy``

Is anything like that possible in rust?
leaden kettle
#

While not pretty
camera_transform.translation = target_transform.translation.truncate().extend(camera_transform.translation.z)

bold barn
#

Ah truncate()! I've been looking for such a method

dusty skiff
#

Btw you can also use .xy() instead of .truncate() (you might need to use bevy::math::Vec3Swizzles though)

wide wren
#

Also, the opposite of .truncate() is .extend(somevalue)

cyan nacelle
#

I actually kinda wish there was a .z() method Vec2s, so you could do like vec_3.xy().z(0.0), it would work the exact same as extend, but just be slightly shorter (and potentially more confusing hehe)

ember yew
#

i think a Vec3::with_x() etc would make more sense

leaden kettle
#

Would be really neat if we could just position_1.(x, y) = position_2.(x, y) but that would probably need to be implemented on the language level

bold barn
#

Would that be possible with a macro somehow? swizzle!(position_1.(x, y) = position_2.(x, y))