Skip to content

trivialkart_unreal: Add gamepad and keyboard/mouse input support - #126

Open
meeraegoo wants to merge 2 commits into
android:mainfrom
meeraegoo:feat/unreal-controller-support
Open

meeraegoo wants to merge 2 commits into
android:mainfrom
meeraegoo:feat/unreal-controller-support

Conversation

@meeraegoo

@meeraegoo meeraegoo commented Nov 12, 2026 •

Copy link
Copy Markdown

Summary

Adds full controller (gamepad) and keyboard/mouse input support to the TrivialKart Unreal sample (trivialkart/trivialkart_unreal) while preserving compatibility with both Unreal Engine 5.7 and 5.8.

Key Changes

  • Multi-Input Mode Management (Touch / Gamepad / KeyboardMouse):
    • Added FTrivialKartGamepadInputProcessor (IInputProcessor) and expanded ATrivialKartPlayerController for seamless runtime switching across touch, Bluetooth/USB controllers, and keyboard/mouse with dynamic input guide banners.
  • Zero-Asset-Churn Gameplay Input Registration:
    • Clones IMC_Default transiently at runtime to register gamepad (A, D-Pad Right, Left Stick Right, Left/Right Triggers) and keyboard/mouse bindings in C++, with UTrivialKartPositiveTriggerModifier guarding against negative HID (-1.0) and Android DualSense (+0.50) resting trigger values.
  • Full Controller UI Navigation & High-Contrast Focus:
    • Added D-Pad and Left Stick navigation (with deadzone hysteresis and neutral latch), LB/RB (Tab/Shift+Tab) tab switching, BackButton focus, and high-visibility focus outlines across PlayBoard, Garage, Store, and PGS menus.
  • Platform & Build Configuration:
    • Configured Android controller/keyboard/mouse settings and primary-user device mapping policy in DefaultEngine.ini and DefaultInput.ini, updated .Target.cs to Latest for UE 5.7/5.8 compatibility, and updated README.md.

Testing

  • Built and packaged Android arm64 APK and verified on physical Android device with Bluetooth controller and touch handoff:
    • Verified kart driving via triggers, A, D-Pad Right, Left Stick Right, and touch hold pad (no resting trigger auto-drive).
    • Verified HUD menu entry/exit toggle via D-Pad & Left Stick Up/Down, horizontal menu/item navigation, tab switching, close button navigation, and clean fallback to Touch mode upon controller disconnect.

Reviewers

cc @natetrost @stmazoni @wayneluzw @RKS13D

- Add FTrivialKartGamepadInputProcessor (Slate IInputProcessor) and
  ATrivialKartPlayerController multi-input mode management for seamless
  switching across Touch, Gamepad, and Keyboard/Mouse.
- Register controller and keyboard gameplay bindings dynamically on a
  transient runtime clone of IMC_Default with UTrivialKartPositiveTriggerModifier
  to guard against negative HID (-1.0) and Android DualSense (+0.50) resting
  trigger values while keeping UE 5.7 asset compatibility.
- Add full D-Pad, analog stick (with hysteresis and modal latch), shoulder/Tab
  tab-switching, BackButton focus, and high-contrast focus visuals across
  PlayBoardWidget, StoreWidget, GarageWidget, PGSWidget, and SelectableItem.
- Configure Android controller/keyboard/mouse runtime settings and device
  mapping policy in DefaultEngine.ini and DefaultInput.ini, update .gitignore,
  and document controls in README.md.
@meeraegoo

Copy link
Copy Markdown
Author

Hi @natetrost @stmazoni @wayneluzw @RKS13D — please take a look when you have a chance! Thanks!

@natetrost natetrost left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Saw a couple things in agent review that seem reasonable. The switch pro is a bit of a weird controller.

return nullptr;
}

bool ATrivialKartHUD::HandleGamepadKey(const FKey& Key, bool bIsPressed, bool bIsRepeat)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

While ZOrder = 10 blocks touch and mouse clicks via Slate hit-testing, FTrivialKartGamepadInputProcessor intercepts controller and keyboard input before Slate hit-testing. Because HandleGamepadKey(), IsUIBlockingInput(), and IsStickNavigationEnabled() ignore EWidgetType::Loading, controller and keyboard users can continue purchasing items, switching tabs, closing menus (B / Esc / Android_Back), or driving the kart underneath the Loading overlay while cloud save I/O is in flight—racing against OnCloudReadComplete replacing SaveGameInstance.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 684a33a. IsLoadingOpen() now blocks gamepad/keyboard UI navigation, Android_Back, pointer presses, and gameplay driving (IsUIBlockingInput() / UTrivialKartDriveInputModifier), and showing Loading cancels any pending UI presses and latches stick navigation until neutral.

}
}

void ATrivialKartHUD::RemoveWidgetFromScreen(const EWidgetType WidgetType)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

BeginPlay() removed the initial AddWidgetToScreen(EWidgetType::Loading, 10) call (line 157) and added ATrivialKartHUD::RefreshActiveSubMenu() (lines 328–338), which has no callers anywhere in the codebase. If a player opens Store or Garage before initial async OnCloudReadComplete finishes (or when an in-menu cloud save completes), RemoveWidgetFromScreen(EWidgetType::Loading) either returns early at !ExistingPtr (line 203) or removes Loading without calling RefreshActiveSubMenu(), leaving car ownership (CarsOwned) and focus stale.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 684a33a. Restored the initial AddWidgetToScreen(EWidgetType::Loading, 10) in BeginPlay() (with a fallback timeout if cloud sign-in/sync is unavailable) and wired RefreshActiveSubMenu() when cloud read/save completes so open Store / Garage modals refresh CarsOwned and focus state immediately.

#include "InputCoreTypes.h"
#include "UObject/WeakObjectPtr.h"

class ATrivialKartPlayerController;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

  1. Broken triggers on digital-trigger gamepads: ProcessKeyEvent (lines 473–480) swallows EKeys::Gamepad_LeftTrigger and EKeys::Gamepad_RightTrigger whenever bIsPressed && CachedAxis < 0.65f, and GetOrCreateGameplayMappingContext() (lines 166–202) only maps Gamepad_LeftTriggerAxis / Gamepad_RightTriggerAxis to MoveAction. On controllers with digital microswitch triggers or Android HID profiles that emit KEYCODE_BUTTON_L2 / KEYCODE_BUTTON_R2 without AXIS_LTRIGGER / AXIS_RTRIGGER events (e.g., Nintendo Switch Pro Controller, Joy-Cons, and many mobile Bluetooth/USB-C controllers), CachedLeftTrigger and CachedRightTrigger remain 0.0f permanently. Every trigger press is dropped at line 478 before switching to Gamepad mode or driving the kart, breaking the primary prompt ("Hold Trigger, A, or D-Pad Right to drive").

  2. Unmatched KeyUp / key-repeat leak & dead code on analog controllers: On analog controllers (Xbox, DualSense), Unreal synthesizes KeyDown for Gamepad_LeftTrigger / Gamepad_RightTrigger once when the trigger crosses its low internal threshold (~0.2f–0.5f, while CachedAxis < 0.65f). Line 478 swallows that KeyDown without recording RawKey in ConsumedPressedKeys. If Android later generates key-repeat KeyDown events while the trigger is held past 0.65f, they bypass line 476, and releasing the trigger leaks an unmatched KeyUp at lines 589–591. Meanwhile, the trigger check in PlayBoardWidget.cpp:682–689 is unreachable because ResolveFallbackUIKey returns EKeys::Invalid for trigger keys.

Suggested fix: Track whether each trigger actually reports non-zero analog axis data (bHasLeftTriggerAnalog / bHasRightTriggerAnalog, reset in ResetState()), consume digital trigger keys cleanly (both press/repeat and matching release) only when analog trigger data is present, and map Gamepad_LeftTrigger / Gamepad_RightTrigger in StandardDriveKeys:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 684a33a. Trigger analog capability (bHasLeftTriggerAnalog / bHasRightTriggerAnalog) and digital trigger state are now tracked per FInputDeviceId, Gamepad_LeftTrigger / Gamepad_RightTrigger are mapped alongside analog trigger axes in GetOrCreateGameplayMappingContext(), synthesized digital trigger press/repeat/release events on analog-trigger pads are consumed symmetrically via ConsumedPressedKeys, and the unreachable trigger check in PlayBoardWidget was removed.

protected:
UPROPERTY()
TArray<UCheckBox*> CheckBoxes;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

~1,300 lines of duplicated modal navigation, tab-highlight, and item-focus logic across StoreWidget, GarageWidget, and PGSWidget

Locations:

StoreWidget.h & StoreWidget.cpp
GarageWidget.h & GarageWidget.cpp
PGSWidget.h & PGSWidget.cpp

Problem: UStoreWidget (+612 lines) and UGarageWidget (+626 lines) are ~95% line-for-line copies of the exact same implementation: Ensure*TabHighlightBorder, the WidgetTree->ForEachWidget hit-test pass, BackButton style caching and render-scale highlighting, TabHighlightBorders construction/rendering, SetCheckBoxState, SelectTabByIndex, GatherSelectableItems, RefreshAllItemsOwnership, OnSelectableItemInteracted/Unhovered/Clicked, CancelPendingPress, RefreshGamepadFocus, and HandleGamepadKey (differing only in UGarageWidget::FindActiveCarItemIndex()). UPGSWidget (+383 lines) duplicates a third copy of the tab-bar, BackButton, and hit-test setup.

Because this project is a public developer sample meant to teach Unreal Android controller integration, ~1,300 lines of copy-pasted UI state-machine code obscures the pattern being demonstrated and triples maintenance surface.

Suggested fix: Extract a common base widget class (e.g., UTrivialKartTabbedModalWidget : public UUserWidget) owning BackButton, ContentSwitcher, CheckBoxes, TabHighlightBorders, ActiveTabIndex, FocusedItemIndex, RefreshGamepadFocus(), and HandleGamepadKey(), with a small virtual hook for subclass customization:

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Fixed in 684a33a. Extracted UTrivialKartTabbedModalWidget (plus shared brush/hit-test helpers in TrivialKartUIStyle.h) so UStoreWidget, UGarageWidget, and UPGSWidget share the common modal navigation, tab-highlight, BackButton focus, and USelectableItem focus/ownership logic, leaving only widget-specific hooks in each subclass.

…controller polish

- Extract UTrivialKartTabbedModalWidget and TrivialKartUIStyle to share modal
  navigation, tab switching, item focus caching, and rounded highlight styling
  across StoreWidget, GarageWidget, and PGSWidget.
- Block gamepad, keyboard, and pointer input while the Loading overlay is
  active, restore initial BeginPlay Loading display with a cloud-sync timeout
  fallback, and refresh open submenus via RefreshActiveSubMenu() when cloud
  save operations finish.
- Support both digital-only triggers (e.g. Nintendo Switch Pro / Joy-Con) and
  analog triggers (including Android DualSense +0.50 resting offset) per
  FInputDeviceId via UTrivialKartDriveInputModifier without dynamic mapping
  context rebuild lockouts, and guard against DualSense touchpad phantom Touch1.
- Track per-device controller families (Xbox A, PlayStation X, Nintendo Switch B)
  for instant HUD prompt switching across simultaneously connected Bluetooth
  controllers, including multiple identical controllers and hotplug/disconnect.
- Inset PlayBoard HUD button focus frames and SelectableItem card highlights so
  button labels stay centered and focus borders never clip on curved phone
  screen corners or ScrollBox bounds.
@meeraegoo

Copy link
Copy Markdown
Author

Thanks for the review @natetrost! Addressed all review comments in 684a33a along with on-device fixes verified across Xbox, PlayStation DualSense, and Nintendo Switch Pro controllers (per-device digital/analog trigger handling, dynamic A / X / B prompt switching across simultaneously connected controllers, DualSense touchpad phantom-touch guard, and screen-safe HUD focus frames). Ready for another look when you have a moment.

@natetrost

Copy link
Copy Markdown
Contributor

LGTM, go ahead and merge, or let me know if you need me to do it.

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

Successfully merging this pull request may close these issues.

2 participants