Dragging and Dropping in Actionscript 3.0

Ok this is a little tip for Dragging your clips on Actionscript 3.0, remember how we used a lot of tricks in Flash to drag a clip from other points that weren’t the anchor point , well in Actionscript 3.0 (herenow AS3) is quite simple to do that by using the new Point class.
Class Point.
Package flash.geom
Class public class Point
InheritancePoint Object
Language version: ActionScript 3.0
Player version: Flash Player 9
The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.

So here’s a very short example made in AS3 in wish no matter where your grab the Sprite, it will be dragged from that specific Point.
Heres the example :

The Flash plugin is required to view this object.


Open in New Window

Here’s the code:

?View Code ACTIONSCRIPT3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
bear.addEventListener(MouseEvent.MOUSE_DOWN, startbearDrag);
stage.addEventListener(MouseEvent.MOUSE_UP, stopbearDrag);
bear.addEventListener(Event.ENTER_FRAME, dragbear);
 
var clickOffset:Point = null;
 
function startbearDrag(event:MouseEvent) {
	clickOffset = new Point(event.localX, event.localY);
}
 
function stopbearDrag(event:MouseEvent) {
	clickOffset = null;
}
 
function dragbear(event:Event) {
	if (clickOffset != null) {
		bear.x = mouseX - clickOffset.x;
		bear.y = mouseY - clickOffset.y;
	}
}


Follow me on Twitter




5 Responses to “Dragging and Dropping in Actionscript 3.0”


  1. 1 Richard

    Um…couldn’t you just use the startDrag and stopDrag functions? By default they drag from where you click, don’t they?

  2. 2 swfgeek

    Maybe I didn’t explain myself too well, I’m know for that :P
    The difference between doing it this way is that you keep the position of the cursor offset and the sprite relative to each other as the user drags; And the second and more important for it’s flexibility it’s that the dragging it’s not tied to the sprite object but to the Point object that gives us plenty of room for playing with our code.

  3. 3 Franky

    I am getting the following error:
    1120: Access of undefined property bear
    Any ideas?

  4. 4 swfgeek

    Hi Franky!!

    That’s probably because you haven’t give the instance name of “bear” to the MovieClip you’re trying to drag, to do so simple name “bear” that clip or substitute “bear” in the code with the name of your clip.

    Hope it’s helps if any trouble comment it here.

    Thanks Dave

  1. 1 GiuseppeSorce » Blog Archive » Drag ‘n drop in AS 3.0

Leave a Reply