What am I going to explain?
I'll explain how to make the code used for dragging objects around. You can use this code for dress up games, but maybe you can think up an other use for it ;)
How are we going to do it?
First draw an object, make it a movieclip give it the instance name object. Note that you can also give an other name to it, but then you'll have to also change it in the code to the name you chose.
After that we'll decide what type of Listeners we want to add...
We want flash to know when the mouse is down so we add this Listener on the object.
object.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
Of course we also want flash to know when the user releases his mouse so we'll add this listener on the listener
object.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
As last listener we'll add a listener that will continuously keep the position of the mouse the same as the object, as long as the left mouse button is down! So we'll use this listener on the object:
object.addEventListener(Event.ENTER_FRAME, dragging);
We also want that it doesn't matter where the person clicks on the object, so he can dragg it from any point. We'll use a point variable, I'm calling it distance, but you can call it anything, remember to change the code in that case!
Now we'll say that the distance variable point is null, it doesn't have a value.
var distance: Point = null;
Now we'll start adding the functions to the EventListeners, the first one is the MOUSE_DOWN listener. When the mouse is down the variable point distance will get the position of where there's been clicked.
function startDragging (event:MouseEvent){
distance = new Point (event.localY, event.localX);
}
Afterwards we'll add the code that when the mouse button is released, in other words up, the variable distance point is null.
function stopDragging(event:MouseEvent) {
distance = null;
}
As last code we'll add the function to the ENTER_FRAME listener:
function dragging(event:Event) {
if (distance != null) {
object.x = mouseX - distance.x;
object.y = mouseY - distance.y;
}
}
Note that without the - distance.x and -distance.y the center of the object would pop to the mouse, try it yourself ;)
To help you guys out here's the code all together:
object.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
object.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
object.addEventListener(Event.ENTER_FRAME, dragging;
var distance:Point = null;
function startDragging(event:MouseEvent) {
distance = new Point(event.localX, event.localY);
}
function stopDragging(event:MouseEvent) {
distance = null;
}
function dragging(event:Event) {
if (distance != null) {
object.x = mouseX - distance.x;
object.y = mouseY - distance.y;
}
}
And as last here's a download to the .fla file that you could use.
If you're having problems leave a comment or PM me.
Also leave a comment or PM me if I made a mistake.