Simplified XNA drag and drop
Monday, July 29th, 2013I got a question about how to implement multiple selection with drag and drop, and could see how that might be a challenge to implement to a beginning programmer. So I thought I'd make a codesample to learn from.
When I had finished coding, it struck me that I could refactor the code so the drag and drop part was tucked away in a helperclass. Then all that was needed to use it in any solution was to have the draggable objects implement an interface to let the helperclass
- know the boundaries of the object
- be able to change the position of the object
I expanded the helperclass to notify the object when the mouse was hovering over it, and whether the object was selected, so all that was left for the coder using the helperclass, would be to implement different ways of drawing the object according to what the state of IsMouseOver and IsSelected is.
So without further ado - let me present the DragAndDropController
What you get
It's as easy as this to use the controllerclass in your project:
//declare the controller somewhere on your Game class private DragAndDropController<Item> _dragDropController; //instantiate the controller somewhere _dragDropController = new DragAndDropController<Item>(this, _spriteBatch); //and add it to the Game class' Components Components.Add(_dragDropController); //add the items you want drag-and-drop enabled to the controller _dragDropController.Add(item);
The items that you add to the controller must implement the IDragAndDropItem interface:
Or in code, if you prefer that:
/// <summary> /// Interface describing necessary implementation /// for working with the DragAndDropController. /// </summary> public interface IDragAndDropItem { Vector2 Position { get; set; } bool IsSelected { set; } bool IsMouseOver { set; } bool Contains(Vector2 pointToCheck); Rectangle Border { get; } }
And that's it!
What an interface does
An interface in code is a contract that allows one piece of code (the DragAndDropController in this case) to treat objects of different types in the same way. This means that no matter whether the class implementing the interface is a "PlayerCharacter", a "MoneyToken" or a "PlayingCard", as long as they implement the abovementioned methods, the controllerclass can interact with them .
Video demonstration
The DragAndDropController<T>
Here you can see the public properties and methods of the DragAndDropController
Since it is a generic class you instantiate it to handle the type of your objects, and from then on you can add or remove items of that type to and from the controller.
You can also get the item under the mouse at any time (if any).
Source code
Here is the complete source code