Something I have been struggling allot with is how to code a user interface in XNA so that it may be both powerful, easy to use and easy to understand. My current solution is using a UI Control class that handles all UI elements(Buttons, health bars, all things part of the UI) and is subscribed to mouse move events and mouse pressed events from an Input manager class.
When the mouse move or is pressed the UI controller iterates trough all UI elements to see if the mouse was pressed/moved on that particular element.
This feels like a somewhat bulky solution, having to iterate trough all elements. Is there any other ways of doing this, or are there anything I could change to improve it?
class UIControler { //List containing all UI elements List<UIElement> elements = new List<UIElement>(); //Subscribed to the input mananger´s MousePress event public void LeftMousePress (Point point) { foreach (UIElement element in elements) { if (element.Area.Contains(point)) { element.Funktion(); return; } } } //Subscribed to the Input manager´s MoveMove event public void MouseMove(Point OldPos, Point CurrentPoS) { foreach (UIElement element in elements) { if (element.Area.Contains(CurrentPoS) && !element.Area.Contains(OldPoS)) { element.MouseEnter(); } if(element.Area.Contains(OldPoS)&& !element.Area.Contains(CurrentPoS)) { element.MouseLeave(); } } } }
Here is the base class for all UI elements:
abstract class UIElement { //Where the element exist on the screen. This rectangle is also used when the UI is drawn. Rectangle area; public delegate void Delegatefunktion(); //Called on when the element is pressed Delegatefunktion func; //Called on when the mouse enters it´s area Delegatefunktion mouseenter; //Called on when the mouse leaves it´s area Delegatefunktion mouseleave; }