Hi there,
I am currently refactoring some code before I moving onto implementing new features. So I stumbled over my input handling. It is quite straight foreward and working quite good actually. Nevertheless, I am not sure if this is a proper way to do it and I would rather change it now - if necessary - than later reworking to much of it.
So basically my code looks like this (simplyfied):
In Game1.cs in Update() I pass mouse clicks to my InputHandler class. I made it static since its a pure utility class:
if (mouseState.LeftButton == ButtonState.Pressed)
InputHandler.HandleMouseclick(mousePosition));
In this HandleMousclick of my InputHandler class I check if the click intersects with objects (like a box or chest), or other NPCs standing or UI elements like buttons in the action bar.
public static void HandleMouseclick(Vector2 mousePos)
{
if (UIManager.CheckMousClick(mousePos))
return;
if (WorldObjects.CheckMousClick(mousePos))
return;
if (WorldCharacters.CheckMousClick(mousePos))
return;
}
Last but not least, I loop through the Characters (or objects, or UI elemts) in their respective manager class if the user has clicked on something:
public static bool CheckMousClick(Vector2 mouseWorldPos)
{
foreach (NPC npc in worldCharacters)
{
if (npc.BoundingBox.Contains(mousePos))
{
npc.Interact();
return true;
}
}
return false;
}
That’s it. No rocket science I guess. But somehow I’ve got the feeling this is not really state of the art input handling. it might be the case that there are a lot of NPCs or clickable objects around and I feat looping through all of them might be take too long?
An thoughts on that? Maybe it is good enough for a 2D game but I am not sure, maybe there are better ways to do that.