The "Flag"
The Flash help suggests another approach - attach and release the Mouse_Move event. I like this because no code is called, and there is no need to test some flag, when the mouse is moving ... until the button is pressed.
The next 2 sections show these techniques. Note that the mouse is moving an object named canvas and that the mouse events are connected to the stage.
Using a "flag" Variable
var Drag_Flag:Boolean = false; var Mouse_x:int; stage.addEventListener(MouseEvent.MOUSE_DOWN,canvas_OnMouseDown) stage.addEventListener(MouseEvent.MOUSE_UP, canvas_OnMouseUp) stage.addEventListener(MouseEvent.MOUSE_MOVE,canvas_OnMouseMove) function canvas_OnMouseDown(m:MouseEvent){ Drag_Flag = true; Mouse_x = m.stageX; } function canvas_OnMouseUp(m:MouseEvent){ Drag_Flag = false } function canvas_OnMouseMove(m:MouseEvent){ if (Drag_Flag) { canvas.x -= Mouse_x - m.stageX; Mouse_x = m.stageX; // Save the new position m.updateAfterEvent(); // This makes the scrolling much smoother } }
Adding and Removing an Event
var Mouse_x:int; stage.addEventListener(MouseEvent.MOUSE_DOWN,canvas_OnMouseDown) stage.addEventListener(MouseEvent.MOUSE_UP, canvas_OnMouseUp) function canvas_OnMouseDown(m:MouseEvent){ Mouse_x = m.stageX; stage.addEventListener(MouseEvent.MOUSE_MOVE,canvas_OnMouseMove) } function canvas_OnMouseUp(m:MouseEvent){ stage.removeEventListener(MouseEvent.MOUSE_MOVE,canvas_OnMouseMove) } function canvas_OnMouseMove(m:MouseEvent){ canvas.x -= Mouse_x - m.stageX; Mouse_x = m.stageX; // Save the new position m.updateAfterEvent(); // This makes the scrolling much smoother }
Notes
Drag Class
var m_drag: TMouse = new TMouse; m_drag.Target = stage; m_drag.OnMouseMove = canvas_move; function canvas_move(dX:int, dY:int){ canvas.x -= dX; }
References
Programming ActionScript 3.0 Display programming > Manipulating display objects > Changing position Creating drag-and-drop interactionProvides several examples on how to drag objects. The first example uses the startDrag() method which they admit (and I agree) is fairly limiting. The second example uses the MOUSE_MOVE event and provides much more capability. The third shows how several objects can share the same methods. I strongly suggest reading these.
For related information, scroll to the bottom of the Mouse class help for a custom cursor example - create a graphic that extends Shape, hide the real cursor, draw the graphic, and reposition the image as the mouse moves.
This example suggests disabling the drag and restoring the cursor when the mouse leaves the component (MOUSE_OUT) or the form (MOUSE_LEAVE).
Author: Robert Clemenzi - clemenzi@cpcug.org