#Trouble implementing a click and drag 2d camera

5 messages · Page 1 of 1 (latest)

candid turret
#
pub fn mouse_camera_pan(
    mut camera_query: Query<
        (
            &ActionState<CameraAction>,
            &mut Transform,
            &OrthographicProjection,
        ),
        With<MainCamera>,
    >,
) {
    let Some((action_state, mut transform, projection)) = camera_query.get_single_mut().ok() else {
        return;
    };

    if !action_state.pressed(&CameraAction::MousePan) {
        return;
    }

    // leafwing_input_manager
    let Some(movement_delta) = action_state.axis_pair(&CameraAction::MousePan) else {
        return;
    };

    let movement_delta = Vec2::new(-movement_delta.x(), movement_delta.y());

    let new_pos = transform.translation.xy() + movement_delta * projection.scale * 0.75;

    transform.translation = new_pos.extend(transform.translation.z);
}

This code is what I am currently using to move my camera in my 2d top down game. new_pos is annoyingly being muiltiplied by a magic number, and the number isn't even correct. Without it your camera appears to slide around in the world. What I want is for the cursor to stay in the same position in world space, which I figured could be done just by taking the movement_delta given to me from leafwing_input_manager and multiplying it by the zoom level (projection.scale), but this oddly doesn't work.

main wolf
#

This isn't an answer but have you looked at bevy_mod_picking? It's got some tools to do what you're trying to do and might come out a bit simpler

candid turret
#

I have not looked at bevy_mod_picking, but at a glance it seems nice, and will probably end up using it as I need drag and drop functionality and that is always a bit annoying. Though with a cursory glance at the examples, it doesn't seem like it was made with camera panning in mind.

main wolf
#

What I do for camera panning is I add a UI node that covers the whole content area and add a On<Pointer<Drag>> component to it and pan the camera off delta like you're doing here

#

Might not be a big enough win to switch off your current impl, but it's what I use when I need something like this 🤷‍♂️