Skip to content

Conversation

@apekros
Copy link
Contributor

@apekros apekros commented Dec 23, 2025

Objective

The situation this addresses was kindly diagrammed out by @ickshonpe:

Details image
The closer item to navigate to is the wider rectangle, but as the center is further away, the bottom rectangle would be chosen, which is incorrect.

Solution

This change does edge to edge distance instead of center to center. I have left alignment scoring to use center to center direction but happy to change this too, I was unsure!

Testing

Added a test for the scenario diagrammed above.


@alice-i-cecile alice-i-cecile added this to the 0.18 milestone Dec 23, 2025
@ickshonpe ickshonpe added C-Bug An unexpected or incorrect behavior A-UI Graphical user interfaces, styles, layouts, and widgets A-App Bevy apps and plugins S-Needs-Review Needs reviewer attention (from anyone!) to move forward D-Straightforward Simple bug fixes and API improvements, docs, test and examples and removed A-App Bevy apps and plugins labels Dec 23, 2025
@ickshonpe ickshonpe self-requested a review December 23, 2025 09:23
@ickshonpe
Copy link
Contributor

Going to be out today, but I'll try and find time for a review this evening.

Copy link
Contributor

@ickshonpe ickshonpe left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good.

I made some modifications to the auto_directional_navigation example and everything checks out:

Screenshot 2025-12-26 142031

On main, it finds that the closest node to "button 1" is "button 3", despite it being much further away than "button 2". Worse, if you navigate to "button 2" from "button 3" you can't then go left to "button 1" as the distance between their centres is greater than the max distance limit.

With this PR, you can navigate from "button 1" to "button 2" and back, as expected.

auto_directional_navigation.rs
```rust
/! Demonstrates automatic directional navigation with zero configuration.
//!
//! Unlike the manual `directional_navigation` example, this shows how to use automatic
//! navigation by simply adding the `AutoDirectionalNavigation` component to UI elements.
//! The navigation graph is automatically built and maintained based on screen positions.
//!
//! This is especially useful for:
//! - Dynamic UIs where elements may be added, removed, or repositioned
//! - Irregular layouts that don't fit a simple grid pattern
//! - Prototyping where you want navigation without tedious manual setup
//!
//! The automatic system finds the nearest neighbor in each compass direction for every node,
//! completely eliminating the need to manually specify navigation relationships.

use core::time::Duration;

use bevy::{
camera::NormalizedRenderTarget,
input_focus::{
directional_navigation::{
AutoDirectionalNavigation, AutoNavigationConfig, DirectionalNavigation,
DirectionalNavigationPlugin,
},
InputDispatchPlugin, InputFocus, InputFocusVisible,
},
math::{CompassOctant, Dir2},
picking::{
backend::HitData,
pointer::{Location, PointerId},
},
platform::collections::HashSet,
prelude::*,
};

fn main() {
App::new()
// Input focus is not enabled by default, so we need to add the corresponding plugins
.add_plugins((
DefaultPlugins,
InputDispatchPlugin,
DirectionalNavigationPlugin,
))
// This resource is canonically used to track whether or not to render a focus indicator
// It starts as false, but we set it to true here as we would like to see the focus indicator
.insert_resource(InputFocusVisible(true))
// Configure auto-navigation behavior
.insert_resource(AutoNavigationConfig {
// Require at least 10% overlap in perpendicular axis for cardinal directions
min_alignment_factor: 0.1,
// Don't connect nodes more than 500 pixels apart
max_search_distance: Some(500.0),
// Prefer nodes that are well-aligned
prefer_aligned: true,
})
.init_resource::()
.add_systems(Startup, setup_scattered_ui)
// Navigation graph is automatically maintained by DirectionalNavigationPlugin!
// No manual system needed - just add AutoDirectionalNavigation to entities.
// Input is generally handled during PreUpdate
.add_systems(PreUpdate, (process_inputs, navigate).chain())
.add_systems(
Update,
(
highlight_focused_element,
interact_with_focused_button,
reset_button_after_interaction,
update_focus_display,
update_key_display,
),
)
.add_observer(universal_button_click_behavior)
.run();
}

const NORMAL_BUTTON: Srgba = bevy::color::palettes::tailwind::BLUE_400;
const PRESSED_BUTTON: Srgba = bevy::color::palettes::tailwind::BLUE_500;
const FOCUSED_BORDER: Srgba = bevy::color::palettes::tailwind::BLUE_50;

/// Marker component for the text that displays the currently focused button
#[derive(Component)]
struct FocusDisplay;

/// Marker component for the text that displays the last key pressed
#[derive(Component)]
struct KeyDisplay;

// Observer for button clicks
fn universal_button_click_behavior(
mut click: On<Pointer>,
mut button_query: Query<(&mut BackgroundColor, &mut ResetTimer)>,
) {
let button_entity = click.entity;
if let Ok((mut color, mut reset_timer)) = button_query.get_mut(button_entity) {
color.0 = PRESSED_BUTTON.into();
reset_timer.0 = Timer::from_seconds(0.3, TimerMode::Once);
click.propagate(false);
}
}

#[derive(Component, Default, Deref, DerefMut)]
struct ResetTimer(Timer);

fn reset_button_after_interaction(
time: Res,
mut query: Query<(&mut ResetTimer, &mut BackgroundColor)>,
) {
for (mut reset_timer, mut color) in query.iter_mut() {
reset_timer.tick(time.delta());
if reset_timer.just_finished() {
color.0 = NORMAL_BUTTON.into();
}
}
}

/// Spawn a scattered layout of buttons to demonstrate automatic navigation.
///
/// Unlike a regular grid, these buttons are irregularly positioned,
/// but auto-navigation will still figure out the correct connections!
fn setup_scattered_ui(mut commands: Commands, mut input_focus: ResMut) {
commands.spawn(Camera2d);

// Create a full-screen background node
let root_node = commands
    .spawn(Node {
        width: percent(100),
        height: percent(100),
        ..default()
    })
    .id();

// Instructions
let instructions = commands
    .spawn((
        Text::new(
            "Automatic Navigation Demo\n\n\
             Use arrow keys or D-pad to navigate.\n\
             Press Enter or A button to interact.\n\n\
             Buttons are scattered irregularly,\n\
             but navigation is automatic!",
        ),
        Node {
            position_type: PositionType::Absolute,
            left: px(20),
            top: px(20),
            width: px(280),
            padding: UiRect::all(px(12)),
            border_radius: BorderRadius::all(px(8)),
            ..default()
        },
        BackgroundColor(Color::srgba(0.1, 0.1, 0.1, 0.8)),
    ))
    .id();

// Focus display - shows which button is currently focused
commands.spawn((
    Text::new("Focused: None"),
    FocusDisplay,
    Node {
        position_type: PositionType::Absolute,
        left: px(20),
        bottom: px(80),
        width: px(280),
        padding: UiRect::all(px(12)),
        border_radius: BorderRadius::all(px(8)),
        ..default()
    },
    BackgroundColor(Color::srgba(0.1, 0.5, 0.1, 0.8)),
    TextFont {
        font_size: 20.0,
        ..default()
    },
));

// Key display - shows the last key pressed
commands.spawn((
    Text::new("Last Key: None"),
    KeyDisplay,
    Node {
        position_type: PositionType::Absolute,
        left: px(20),
        bottom: px(20),
        width: px(280),
        padding: UiRect::all(px(12)),
        border_radius: BorderRadius::all(px(8)),
        ..default()
    },
    BackgroundColor(Color::srgba(0.5, 0.1, 0.5, 0.8)),
    TextFont {
        font_size: 20.0,
        ..default()
    },
));

let first_button = commands
    .spawn((
        Button,
        Node {
            position_type: PositionType::Absolute,
            left: px(400),
            top: px(200),
            width: px(100),
            height: px(500),
            border: UiRect::all(px(4)),
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            border_radius: BorderRadius::all(px(12)),
            ..default()
        },
        // This is the key: just add this component for automatic navigation!
        AutoDirectionalNavigation::default(),
        ResetTimer::default(),
        BackgroundColor::from(NORMAL_BUTTON),
        Name::new("Button 1"),
    ))
    .with_child((
        Text::new("Button 1"),
        TextLayout {
            justify: Justify::Center,
            ..default()
        },
    ))
    .id();

input_focus.set(first_button);

commands
    .spawn((
        Button,
        Node {
            position_type: PositionType::Absolute,
            left: px(600),
            top: px(300),
            width: px(400),
            height: px(100),
            border: UiRect::all(px(4)),
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            border_radius: BorderRadius::all(px(12)),
            ..default()
        },
        // This is the key: just add this component for automatic navigation!
        AutoDirectionalNavigation::default(),
        ResetTimer::default(),
        BackgroundColor::from(NORMAL_BUTTON),
        Name::new("Button 2"),
    ))
    .with_child((
        Text::new("Button 2"),
        TextLayout {
            justify: Justify::Center,
            ..default()
        },
    ));

commands
    .spawn((
        Button,
        Node {
            position_type: PositionType::Absolute,
            left: px(700),
            top: px(500),
            width: px(100),
            height: px(100),
            border: UiRect::all(px(4)),
            justify_content: JustifyContent::Center,
            align_items: AlignItems::Center,
            border_radius: BorderRadius::all(px(12)),
            ..default()
        },
        // This is the key: just add this component for automatic navigation!
        AutoDirectionalNavigation::default(),
        ResetTimer::default(),
        BackgroundColor::from(NORMAL_BUTTON),
        Name::new("Button 3"),
    ))
    .with_child((
        Text::new("Button 3"),
        TextLayout {
            justify: Justify::Center,
            ..default()
        },
    ));

commands.entity(root_node).add_children(&[instructions]);

}

// Action state and input handling (same as the manual navigation example)
#[derive(Debug, PartialEq, Eq, Hash)]
enum DirectionalNavigationAction {
Up,
Down,
Left,
Right,
Select,
}

impl DirectionalNavigationAction {
fn variants() -> Vec {
vec![
DirectionalNavigationAction::Up,
DirectionalNavigationAction::Down,
DirectionalNavigationAction::Left,
DirectionalNavigationAction::Right,
DirectionalNavigationAction::Select,
]
}

fn keycode(&self) -> KeyCode {
    match self {
        DirectionalNavigationAction::Up => KeyCode::ArrowUp,
        DirectionalNavigationAction::Down => KeyCode::ArrowDown,
        DirectionalNavigationAction::Left => KeyCode::ArrowLeft,
        DirectionalNavigationAction::Right => KeyCode::ArrowRight,
        DirectionalNavigationAction::Select => KeyCode::Enter,
    }
}

fn gamepad_button(&self) -> GamepadButton {
    match self {
        DirectionalNavigationAction::Up => GamepadButton::DPadUp,
        DirectionalNavigationAction::Down => GamepadButton::DPadDown,
        DirectionalNavigationAction::Left => GamepadButton::DPadLeft,
        DirectionalNavigationAction::Right => GamepadButton::DPadRight,
        DirectionalNavigationAction::Select => GamepadButton::South,
    }
}

}

#[derive(Default, Resource)]
struct ActionState {
pressed_actions: HashSet,
}

fn process_inputs(
mut action_state: ResMut,
keyboard_input: Res<ButtonInput>,
gamepad_input: Query<&Gamepad>,
) {
action_state.pressed_actions.clear();

for action in DirectionalNavigationAction::variants() {
    if keyboard_input.just_pressed(action.keycode()) {
        action_state.pressed_actions.insert(action);
    }
}

for gamepad in gamepad_input.iter() {
    for action in DirectionalNavigationAction::variants() {
        if gamepad.just_pressed(action.gamepad_button()) {
            action_state.pressed_actions.insert(action);
        }
    }
}

}

fn navigate(action_state: Res, mut directional_navigation: DirectionalNavigation) {
let net_east_west = action_state
.pressed_actions
.contains(&DirectionalNavigationAction::Right) as i8
- action_state
.pressed_actions
.contains(&DirectionalNavigationAction::Left) as i8;

let net_north_south = action_state
    .pressed_actions
    .contains(&DirectionalNavigationAction::Up) as i8
    - action_state
        .pressed_actions
        .contains(&DirectionalNavigationAction::Down) as i8;

// Use Dir2::from_xy to convert input to direction, then convert to CompassOctant
let maybe_direction = Dir2::from_xy(net_east_west as f32, net_north_south as f32)
    .ok()
    .map(CompassOctant::from);

if let Some(direction) = maybe_direction {
    match directional_navigation.navigate(direction) {
        Ok(_entity) => {
            // Successfully navigated
        }
        Err(_e) => {
            // Navigation failed (no neighbor in that direction)
        }
    }
}

}

fn update_focus_display(
input_focus: Res,
button_query: Query<&Name, With>,
mut display_query: Query<&mut Text, With>,
) {
if let Ok(mut text) = display_query.single_mut() {
if let Some(focused_entity) = input_focus.0 {
if let Ok(name) = button_query.get(focused_entity) {
**text = format!("Focused: {}", name);
} else {
**text = "Focused: Unknown".to_string();
}
} else {
**text = "Focused: None".to_string();
}
}
}

fn update_key_display(
keyboard_input: Res<ButtonInput>,
gamepad_input: Query<&Gamepad>,
mut display_query: Query<&mut Text, With>,
) {
if let Ok(mut text) = display_query.single_mut() {
// Check for keyboard inputs
for action in DirectionalNavigationAction::variants() {
if keyboard_input.just_pressed(action.keycode()) {
let key_name = match action {
DirectionalNavigationAction::Up => "Up Arrow",
DirectionalNavigationAction::Down => "Down Arrow",
DirectionalNavigationAction::Left => "Left Arrow",
DirectionalNavigationAction::Right => "Right Arrow",
DirectionalNavigationAction::Select => "Enter",
};
**text = format!("Last Key: {}", key_name);
return;
}
}

    // Check for gamepad inputs
    for gamepad in gamepad_input.iter() {
        for action in DirectionalNavigationAction::variants() {
            if gamepad.just_pressed(action.gamepad_button()) {
                let button_name = match action {
                    DirectionalNavigationAction::Up => "D-Pad Up",
                    DirectionalNavigationAction::Down => "D-Pad Down",
                    DirectionalNavigationAction::Left => "D-Pad Left",
                    DirectionalNavigationAction::Right => "D-Pad Right",
                    DirectionalNavigationAction::Select => "A Button",
                };
                **text = format!("Last Key: {}", button_name);
                return;
            }
        }
    }
}

}

fn highlight_focused_element(
input_focus: Res,
input_focus_visible: Res,
mut query: Query<(Entity, &mut BorderColor)>,
) {
for (entity, mut border_color) in query.iter_mut() {
if input_focus.0 == Some(entity) && input_focus_visible.0 {
*border_color = BorderColor::all(FOCUSED_BORDER);
} else {
*border_color = BorderColor::DEFAULT;
}
}
}

fn interact_with_focused_button(
action_state: Res,
input_focus: Res,
mut commands: Commands,
) {
if action_state
.pressed_actions
.contains(&DirectionalNavigationAction::Select)
&& let Some(focused_entity) = input_focus.0
{
commands.trigger(Pointer:: {
entity: focused_entity,
pointer_id: PointerId::Mouse,
pointer_location: Location {
target: NormalizedRenderTarget::None {
width: 0,
height: 0,
},
position: Vec2::ZERO,
},
event: Click {
button: PointerButton::Primary,
hit: HitData {
camera: Entity::PLACEHOLDER,
depth: 0.0,
position: None,
normal: None,
},
duration: Duration::from_secs_f32(0.1),
},
});
}
}

</pre>
</details>



@ickshonpe ickshonpe added S-Ready-For-Final-Review This PR has been approved by the community. It's ready for a maintainer to consider merging it and removed S-Needs-Review Needs reviewer attention (from anyone!) to move forward labels Dec 28, 2025
@alice-i-cecile alice-i-cecile added this pull request to the merge queue Dec 30, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to a conflict with the base branch Dec 30, 2025
@alice-i-cecile
Copy link
Member

Please let me know when merge conflicts are fixed :)

@apekros apekros force-pushed the apekros/directional_nav branch from 067ac25 to ee320d6 Compare December 30, 2025 22:36
@apekros
Copy link
Contributor Author

apekros commented Dec 30, 2025

Please let me know when merge conflicts are fixed :)

@alice-i-cecile should be all good now :)

@alice-i-cecile alice-i-cecile added this pull request to the merge queue Dec 31, 2025
Merged via the queue into bevyengine:main with commit f4b2b6e Dec 31, 2025
38 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

A-UI Graphical user interfaces, styles, layouts, and widgets C-Bug An unexpected or incorrect behavior D-Straightforward Simple bug fixes and API improvements, docs, test and examples S-Ready-For-Final-Review This PR has been approved by the community. It's ready for a maintainer to consider merging it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants