Handling Input (Click on objects)

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.

It would really have to be a lot for this to be a problem, but in that case you could use a 2D spatial data structure to store your clickables. For example store your clickables in a uniform grid, when a click is detected map it to the cell of the grid that it’s in and only check for intersection with clickables inside that cell. But that’s all probably not necessary and what you have now will suffice in most cases.

Hm, okay. Maybe I am too concerned about non existing issues :smiley:
But I rather think about it a bit too much than too little ^^

In that case you’ll find this project interesting (at least the readme.md)

1 Like