Manually dragging an object


/ Published in: ActionScript 3
Save to your folder(s)

Using StartDrag can be problematic and buggy in Flash. I've found that sometimes you don't get the position of the object your dragging updated and it can really mess with any tweens and effects you apply on the object you are dragging afterward. Manually dragging an object is usually better. This code will do the job for you.

There's a lot of extra baggage in here but you can see the general point of it.


Copy this code and paste it in your HTML
  1. //------------------------------------------------------------------------------------
  2. private function startDragHandler(e:MouseEvent = null):void
  3. {
  4. /*
  5. Set custom cursor
  6. */
  7. //if(!dragCursor) dragCursor = new DragCursor();
  8. CursorManager.setCursor(DragCursor as Class,CursorManagerPriority.HIGH,0,0);
  9.  
  10. isMouseOffStage = false;
  11. this.stage.addEventListener(Event.MOUSE_LEAVE,mouseLeftStage);
  12. this.stage.addEventListener(MouseEvent.MOUSE_OUT,mouseOutStage);
  13. this.stage.addEventListener(MouseEvent.MOUSE_OVER,mouseOverStage);
  14. this.stage.addEventListener(MouseEvent.MOUSE_UP,stopDragHandler);
  15. if(DataModel.getInstance().isAllowDragShirt)
  16. {
  17.  
  18. moveFromPointX = this.mouseX;
  19. moveFromPointY = this.mouseY;
  20.  
  21. addEventListener(Event.ENTER_FRAME,draggingHandler);
  22. }
  23. }
  24. //------------------------------------------------------------------------------------
  25. private function draggingHandler(e:Event = null):void
  26. {
  27. var targetX:Number = this.x+(this.mouseX-moveFromPointX);
  28. var targetY:Number = this.y+(this.mouseY-moveFromPointY);
  29.  
  30. if(targetX>0 || targetX<maxMoveX) targetX = this.x;
  31. if(targetY>0 || targetY<=maxMoveY) targetY = this.y;
  32.  
  33. this.x = targetX;
  34. this.y = targetY;
  35.  
  36. moveFromPointX = this.mouseX;
  37. moveFromPointY = this.mouseY;
  38. }
  39. //------------------------------------------------------------------------------------
  40. private function stopDragHandler(e:MouseEvent = null):void
  41. {
  42. moveFromPointX=this.x;
  43. moveFromPointY=this.y;
  44.  
  45. CursorManager.removeAllCursors();
  46. if(DataModel.getInstance().isBusy) CursorManager.setBusyCursor();
  47.  
  48. this.stage.removeEventListener(Event.MOUSE_LEAVE,mouseLeftStage);
  49. this.stage.removeEventListener(MouseEvent.MOUSE_OUT,mouseOutStage);
  50. this.stage.removeEventListener(MouseEvent.MOUSE_OVER,mouseOverStage);
  51.  
  52. this.removeEventListener(Event.ENTER_FRAME,draggingHandler);
  53. //stopDrag();
  54. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.