tags:

views:

93

answers:

3

Hey guys,

I've got an XNA project that will be drawing several objects on the screen. I would like the user to be able to interact with those items. So I'm trying to build a method that checks to see which object the mouse is over, out of those which is the top most, and then fire an OnClick event for that object.

Checking for the things above is not the problem, but where to actually put that logic is most of the issue.

My initial feeling is that the checking should be handled by a master object - since it doesn't make sense for an object, who ideally knows only about itself, to determine information about the other objects. However, calling OnClick events remotely from the master object seems to be counter-intuitive as well.

What's the best practice in this situation?

Thanks,
Tyler

+2  A: 

Don't put the logic in the event handler. Instead have the event handler call another method, passing the clicked object as argument:

// inside the OnClick event handler
ActOnObject(clickedObject);

Then you can call the same method anywhere else in the code, for any object:

ActOnObject(GetObjectUnderMouse()):
Fredrik Mörk
A: 

I would probably have something like an "ObjectManager", a class that would hold a collection of the objects and would handle the finding of the current object that should be clicked upon, and then call the click function on that object. Since the object itself isnt handling the click (it could but in my example technically the overall game itself, or possibly the ObjectManager is the one that catches the click) then i would just take the object that you want to click on and call something like

Object.Click(whatever parameters are logical for your situation)

in the end I think I am suggesting a very similar approach as Fredrik, however the main difference is I personally prefer the "Object" to know what should be done with the click, and thus call the function on the object itself - which might be what you would do in the function suggested above as well...

David Larrabee
A: 

Well , for graphical objects (textures , sprites or the kind ..)

public MyObject()
{ 
  ....

  public AreTheseMyCoordinates(int X, int Y);

}

Where , you get the screen coordinates of the mouse position.

Or you can make a Helper Class:

public static MouseHelper
{
  public static IsObjectClicked(MyObject obj, int X , int Y)
  {
     ....
  }
}

I`d go with the static helper.

GamiShini