Here’s a little AS3 draggable Joystick that bounces back into position with Tweener
Something so basic in AS2 can lead you on a merry little dance in AS3 and I thought I ‘d share some code, there are loads of basic AS3 D&D examples online like this of how to set up dragging on a movieclip but by applying startDrag on MOUSE_UP and stopDrag on MOUSE_DOWN to the same clip, you’ll fall over when your MOUSE_UP event doesnt occur over that clip (e.g. off stage or the equivalent of the deprecated AS2 onReleaseOutside)
The only explanation I could find online of where onReleaseOutside is implemented in AS3 was in the Flex 2 migration doc and is cryptic to say the least. Given the target audience for this info little better explanation wouldn’t go amiss dudes
So anyway the obvious thing to do is add the listener for MOUSE_UP to the stage and not the object so I did that but the following line:
[code lang="actionscript"]
stage.addEventListener(MouseEvent.MOUSE_UP, mouseReleased);
[/code]
Threw the folowing error:
TypeError: Error #1009: Cannot access a property or method of a null object reference
When I moved this into the document class it was fine; this was only occuring when it was in a movieclip added to stage. Turns out this is related to the display list, the sequencing of the call to addChild() and the availability of the stage object.
Here’s my constructor that was causing the issue
[code lang="actionscript"]
public function Joystick(){
init();
}
[/code]
Once I change it to the code below the problem went away and my call to stage.addListener was valid i.e my problem had been that the stage object had not yet been defined (#1009). This is because my call in the parent (document class) to addChild(joystick) added the joystick to the display list but the constructor for the Joystick instance fired before that so it did not know what stage was a refererence to at that moment.
[code lang="actionscript"]
public function Joystick(){
if (stage) {
init();
}
else addEventListener(Event.ADDED_TO_STAGE, init);
}
[/code]
Heres my commented init function from the document class init function which explains matters better:

I have added an FLA, FlashDevelop Project and associated files for This Example so fill your boots and link me if it’s useful

Recent Comments