13.08.2012 Views

ACTIONSCRIPT 3 Developer’s Guide en

ACTIONSCRIPT 3 Developer’s Guide en

ACTIONSCRIPT 3 Developer’s Guide en

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>ACTIONSCRIPT</strong> 3.0 DEVELOPER’S GUIDE<br />

Display programming<br />

The following code (adapted from the previous example) allows two display objects, a circle and a square, to be moved<br />

with the mouse. Wh<strong>en</strong>ever the mouse button is pressed over either one, that item is moved to the top of the Stage’s<br />

display list, so that the dragged item always appears on top. (Code that is new or changed from the previous listing<br />

appears in boldface.)<br />

// This code creates a drag-and-drop interaction using the mouse-following<br />

// technique.<br />

// circle and square are DisplayObjects (e.g. MovieClip or Sprite<br />

// instances).<br />

import flash.display.DisplayObject;<br />

import flash.ev<strong>en</strong>ts.MouseEv<strong>en</strong>t;<br />

var offsetX:Number;<br />

var offsetY:Number;<br />

var draggedObject:DisplayObject;<br />

// This function is called wh<strong>en</strong> the mouse button is pressed.<br />

function startDragging(ev<strong>en</strong>t:MouseEv<strong>en</strong>t):void<br />

{<br />

// remember which object is being dragged<br />

draggedObject = DisplayObject(ev<strong>en</strong>t.target);<br />

}<br />

// Record the differ<strong>en</strong>ce (offset) betwe<strong>en</strong> where the cursor was wh<strong>en</strong><br />

// the mouse button was pressed and the x, y coordinate of the<br />

// dragged object wh<strong>en</strong> the mouse button was pressed.<br />

offsetX = ev<strong>en</strong>t.stageX - draggedObject.x;<br />

offsetY = ev<strong>en</strong>t.stageY - draggedObject.y;<br />

// move the selected object to the top of the display list<br />

stage.addChild(draggedObject);<br />

// Tell Flash Player to start list<strong>en</strong>ing for the mouseMove ev<strong>en</strong>t.<br />

stage.addEv<strong>en</strong>tList<strong>en</strong>er(MouseEv<strong>en</strong>t.MOUSE_MOVE, dragObject);<br />

// This function is called wh<strong>en</strong> the mouse button is released.<br />

function stopDragging(ev<strong>en</strong>t:MouseEv<strong>en</strong>t):void<br />

{<br />

// Tell Flash Player to stop list<strong>en</strong>ing for the mouseMove ev<strong>en</strong>t.<br />

stage.removeEv<strong>en</strong>tList<strong>en</strong>er(MouseEv<strong>en</strong>t.MOUSE_MOVE, dragObject);<br />

}<br />

Last updated 6/6/2012<br />

177

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!