Hi all
As part of the game I'm working on I needed a drag and drop system that worked closer to how Unity's canvas+event system works. 2d toolkit has a drag and drop system, but it's very simple and only maps a button to your mouse position.
I made up a small enhancement that lets you:
- Hook into events using interfaces
- Events include OnPointerEnter, OnPointerExit, OnDrop, OnBeginDrag, OnEndDrag and OnDrag.
- Failure states that will automatically return your draggable back to its origin position when no dropzone is found.
- Ability to have draggable snap to the pointer on move (the default in tk2d is to keep the distance relative).
- Out-of-parent folder support. Usefull for when you are dragging an item which needs to disable the parent folder without affecting the draggable.
- Public fail state trigger: If you drop an item in your inventory, you will get an "OnEndDragSucceeded" event because the draggable found a dropzone. Once you have the item you can then, for example, do a requirements check against the player attributes and if they don't have high enough stats, you can manually call "TriggerFailedDropEvent". This will call the method that is already implementing IOnEndDragHandler just as if it failed normally.
- Deadzone support: Give the draggable a deadzone distance and the OnBegin handlers wont fire until its exceeded that distance. Very useful for when your draggables also have button click events where you dont want very small movements triggering the drag event.
Now with that, I was wondering if you guys could take a peek and let me know if you spot anything that could be improved. I'll eventually put a final version in the announcements forum with documentation, but I wanted to make sure it was following best practices first. For example, one possible point of contention is that on line 259 of tk2dUIDragItem_Custom.cs I'm using a .Where statement to filter out raycasts that are hitting themselves. Unikron seems to avoid using statements like this, probably to ensure iPhone support, but my alternatives always wound up being big cludgy messes of code. If anyone has any ways to replace that, do let me know.
Download via dropboxtk2dUIDragItem_Custom.cs contains all the code to get the drag and drop to work (well, including tk2d of course). It's an extended version of the tk2dUIDragItem script so bits and pieces might look familiar. There are also two example files called "DragWithIcon" and "DropZOne".
If you want to get an idea of how it works,
the code section of this video is basically how this extension works.