Search code examples
javaandroiduser-interfacedesign-patternsstate-pattern

Best practice: Design pattern for 2D HUD screen navigation


If you have an application with a GUI totally working on 2D drawing, what should be the best practice to handle what to draw and where to touch?

An example for better understanding:
I have a game with a map. On this map I can build houses and stuff.
I also have an information bar which can be extended. On the extended bar I draw some information about the game and it also offers the interface to change different values. If a touch occurs, I have to check if the information bar is extended or not, to determine if I want to change something on the map or something on the bar.

That's done by the State Pattern, but I have some doubt if that's the right one because I think it can be a bit complex because of possible "sub-states".

So basically the question: Is the State Pattern (from GoF) the best practice to handle a pure graphical GUI?


Solution

  • The way this typically works is that the UI is a tree of Control objects. Each Control has some bounding box, and potentially a number of child controls which float above it. When a click occurs, the tree is walked from top-down (which means children before parents, and siblings in order). For each control, you see if the point intersects its bounding box. If so, give the control a chance to handle the click (i.e. some virtual OnClick method). If it does, stop processing, that click is done. Otherwise, keep walking until you get to a control that does handle it.