How do I make a class that for example, handles all startDrag() and stopDrag() events? There is no MovieClip for this class. I want this class to function solely as a handler for events that are used by multiple classes.
I’m making a game and I have lots of items that can be dragged and dropped, and I need a more efficient way rather than putting this code in every single item class.
So is there any other way of doing this? Right now I have to copy and paste this into every class I have that can be dragged and dropped.
public function Weapon1()
{
originalPosition = new Point(x,y);
addEventListener(Event.ENTER_FRAME, onEntrance);
}
public function onEntrance(evt:Event)
{
addEventListener(MouseEvent.MOUSE_DOWN, mousedown);
addEventListener(MouseEvent.MOUSE_UP, mouseup);
}
public function mousedown(evt:MouseEvent)
{
startDrag(true);
}
public function mouseup(evt:MouseEvent)
{
stopDrag();
if(dropTarget)
{
if(dropTarget.parent.name == "slot")
{
this.x = dropTarget.parent.x;
this.y = dropTarget.parent.y;
}
}
else
{
returnToPosition();
}
}
else
{
returnToNewPosition();
}
}
public function returnToPosition()
{
x = originalPosition.x;
y = originalPosition.y;
}
public function returnToNewPosition()
{
x = newPosition.x;
y = newPosition.y;
}
What you need is Inheritance which is one of the four fundamental concepts of object-oriented programming. In OOP, inheritance enables classes to take on the properties and methods of an existing base class (also called a super class).
So; You should create a base class with drag and drop logic and extend that class to create your other derived classes (also called sub-classes).
For example, here is the base class (
Draggable):…and here is the
Weapon1class that extends the base class:As you see; it’s the
extendkeyword that enables inheritance for theWeapon1class.You can go on creating more weapon classes…
Notice that the
Draggableclass also extends theMovieClipclass to gain some other functionality. So, each class you extend fromDraggablewill have the functionality of both theMovieClipandDraggableclasses.References: