Return to Kroll Design home page

Flash Tutorials (with .FLA files included)

 
« Return

ActionScript 3

Dragging, without the startDrag and stopDrag methods

This example allows for the dragging of an object (in this case, the walking man) without using the built-in Flash methods of startDrag and stopDrag. When the user places the mouse over the man and holds the mouse button down, a MouseEvent is generated which captures the X and Y position relative to the man's registration point (mouse event: localX, localY). Also used is the X and Y position of the man relative to the stage (walker_mc.mouseX, walker_mc.mouseY), which gets captured continuously and automatically (no event listener required). For it to work properly, it's not enough to subtract the localX and localY offset from the mouseX and mouseY coordinates -- you must first multiply the offset by the man's resized transformation amount (walker_mc.scaleX and walker_mc.scaleY), and then subtract that adjusted offset from mouseX and mouseY. Clearly, using startDrag and stopDrag is easier than using this technique, but doing it "the hard way" like this gives you more control, which may come in handy depending on the situation.

Download the FLA file



var walker_mc:Walker = new Walker();
walker_mc.x = 200;
walker_mc.y = 200;
walker_mc.scaleX = .5;
walker_mc.scaleY = .5;
walker_mc.buttonMode = true;
addChild(walker_mc);

walker_mc.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownFunction);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpFunction);
walker_mc.addEventListener(Event.ENTER_FRAME, dragWalker);

var locationWithinMan:Point = null;

function mouseDownFunction(myEvent:MouseEvent):void
{
	locationWithinMan = new Point(myEvent.localX, myEvent.localY);		
}

function mouseUpFunction(myEvent:MouseEvent):void
{
	locationWithinMan = null;
}

function dragWalker(myEvent:Event):void
{
	if (locationWithinMan != null)
	{
	walker_mc.x = mouseX - (locationWithinMan.x * walker_mc.scaleX) ;
	walker_mc.y = mouseY - (locationWithinMan.y * walker_mc.scaleX);
	}
}


 
« Return


©2012 Kroll Design    info@KrollDesign.net    781.910.3694
Last modified: 12/31/1969 7:00 PM