Dragging Made Easy
Thursday, March 26th, 2009Drag and Drop has popped its head into my work week about a half dozen times this week which inspired me to post some code of a basic object oriented drag system. It’s not perfect and hitTestPoint would give me a more accurate collision detecation against the circle, but I thought it would be nice to see a simple example.
Here’s a quick rundown
- Array and Loop for setting up the listeners
- Always set the dragging item on top
- Check for the correct detection (Here’s a hint it’s the third box)
- React to the detection
Using the MouseEvent reference defined as e, you can avoid calling the movie clip or button by their original instance name. This gives you, the developer, a more flexible framework to add and delete drag-able items at will.
Source Code
dragdemoquestion
dragdemoquestion
-
-
// D R A G A B L E C L I P S
-
dragArray[0] = box1
-
dragArray[1] = box2
-
dragArray[2] = box3
-
dragArray[3] = box4
-
-
// L I S T E N E R S
-
for(var i:int=0; i<dragArray.length; i++){
-
dragArray[i].addEventListener(MouseEvent.MOUSE_DOWN, onDragClip)
-
dragArray[i].addEventListener(MouseEvent.MOUSE_UP, onStopDragClip)
-
dragArray[i].addEventListener(MouseEvent.MOUSE_OVER, onOverDragClip)
-
dragArray[i].addEventListener(MouseEvent.MOUSE_OUT, onOutDragClip)
-
dragArray[i].buttonMode=true
-
}
-
-
// H A N D L E R S
-
function onDragClip(e:MouseEvent):void{
-
e.target.startDrag()
-
// Make sure what I’m dragging is always on top
-
setChildIndex(MovieClip(e.target), numChildren-1)
-
}
-
function onStopDragClip(e:MouseEvent):void{
-
// stop the drag please
-
e.target.stopDrag()
-
// hey do I know you…
-
if(e.target.hitTestObject(circle1)){
-
if(e.target.name =="box3"){
-
// … if so do some stuff
-
txt_box.text="Drag Me - Winner"
-
centerClip(MovieClip(e.target),circle1)
-
}else{
-
// … nevermind I thought you were someone else
-
txt_box.text="Drag Me - Loser fail"
-
removeChild(MovieClip(e.target))
-
}
-
}
-
}
-
function onOverDragClip(e:MouseEvent):void{
-
// Rollovers… Aren’t they fun
-
e.target.filters = [new GlowFilter(0xFFFF00,.5, 20.0,20.0,2,1,false, false)]
-
}
-
function onOutDragClip(e:MouseEvent):void{
-
// Peace out on the Roll out
-
e.target.filters = null
-
}
-
// C U S T O M M E T H O D S
-
function centerClip(mc1:MovieClip, mc2:MovieClip):void{
-
mc1.x =mc2.x+((mc2.width/2) - (mc1.width/2))
-
mc1.y =mc2.y+ ((mc2.height/2) - (mc1.height/2))
-
}
-
-


