MouseDown and OnRelease Events in AS2

Have you ever had this happen when you are updating or creating a Flash movie using the old AS2?

You create a movie clip with the following code to trap a mouse click on itself.

onMouseDown = function(){
  trace(this._name);
  var sel = int(substring(this._name,3,1));
  trace(sel);
  if (sel > 0){
   _parent.mcWorld["mcE"+sel].play();
   _parent.mcWorld["mcE"+sel]._visible = true;
  } 
}

You place 9 instances on the stage and run the movie, click on one of the movie clip instances and see this result in the trace window.

mc9
9
mc8
8
mc7
7
mc6
6
mc5
5
mc4
4
mc3
3
mc2
2
mc1
1

Every single instance of the movie clip fired the mouseDown logic but you only clicked on one of them.

Resolving this issue is simple but you need to implement your own state tracking logic. To do that, replace the Action Script code from above with the following.


this.onMouseDown = function(){
     if (this.hitTest(_root._xmouse, _root._ymouse, true)) {
         this.isPressed = true;
         // onPress
     }else{
         this.isPressed = false;
     }
}

this.onRelease = function(){
    if (this.isPressed){
         if (this.hitTest(_root._xmouse, _root._ymouse, true)) {
              trace(this._name);
              var sel = int(substring(this._name,3,1));
              trace(sel);
              if (sel > 0){
                     _parent.mcWorld["mcE"+sel].play();
                     _parent.mcWorld["mcE"+sel]._visible = true;
             }
        }else{
           // onReleaseOutside
        }
    }
 this.isPressed = false;
}

This code simply detects when the mouse button is down and checks if the mouse coordinates are within the bounds of the current movie clip instance. If it is then the action code executes otherwise it ignores the mouse events.

Tags: , , ,

Leave a Reply