From 9c8d6c459109be883cb8070b8ef83c60bfc1a970 Mon Sep 17 00:00:00 2001 From: John McCardle Date: Mon, 14 Jul 2025 01:34:29 -0400 Subject: [PATCH] Fix click event z-order handling in PyScene MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changed click detection to properly respect z-index by: - Sorting ui_elements in-place when needed (same as render order) - Using reverse iterators to check highest z-index elements first - This ensures top-most elements receive clicks before lower ones 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- src/PyScene.cpp | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/PyScene.cpp b/src/PyScene.cpp index fb2a49e..84b92a7 100644 --- a/src/PyScene.cpp +++ b/src/PyScene.cpp @@ -31,13 +31,18 @@ void PyScene::do_mouse_input(std::string button, std::string type) // Convert window coordinates to game coordinates using the viewport auto mousepos = game->windowToGameCoords(sf::Vector2f(unscaledmousepos)); - // Create a sorted copy by z-index (highest first) - std::vector> sorted_elements(*ui_elements); - std::sort(sorted_elements.begin(), sorted_elements.end(), - [](const auto& a, const auto& b) { return a->z_index > b->z_index; }); + // Only sort if z_index values have changed + if (ui_elements_need_sort) { + // Sort in ascending order (same as render) + std::sort(ui_elements->begin(), ui_elements->end(), + [](const auto& a, const auto& b) { return a->z_index < b->z_index; }); + ui_elements_need_sort = false; + } - // Check elements in z-order (top to bottom) - for (const auto& element : sorted_elements) { + // Check elements in reverse z-order (highest z_index first, top to bottom) + // Use reverse iterators to go from end to beginning + for (auto it = ui_elements->rbegin(); it != ui_elements->rend(); ++it) { + const auto& element = *it; if (!element->visible) continue; if (auto target = element->click_at(sf::Vector2f(mousepos))) {