How to Constrain Dragging to an Ellipse

ActionScript 2.0

In an earlier article, we briefly touched on the built-in MovieClip.startDrag() method, which allows dragging to be optionally constrained to a rectangle.  In that same article, we also looked at a way to constrain dragging to a circle, in which case dragging actually meant positioning the movie clip where the mouse was — as long as that area lay within an arbitrary circle.  Here, we will constrain dragging to an ellipse. 

An answer, short and sweet

The following ActionScript assumes a movie clip with the instance name mc.  Type the following into your Actions panel.

mc.origX = mc._x;
mc.origY = mc._y;
mc.onPress = function() {
  this.onEnterFrame = function() {
    var angle:Number = Math.atan2(
      _root._ymouse - this.origY,
      _root._xmouse - this.origX
    );
    if (
      Math.abs(_root._xmouse - this.origX) <=
      Math.abs(Math.cos(angle) * 200)
    ) {
      this._x = _root._xmouse;
    } else {
      this._x = this.origX + (Math.cos(angle) * 200);
    }
    if (
      Math.abs(_root._ymouse - this.origY) <=
      Math.abs(Math.sin(angle) * 100)
    ) {
      this._y = _root._ymouse;
    } else {
      this._y = this.origY + (Math.sin(angle) * 100);
    }
  };
};
mc.onRelease = function() {
  delete this.onEnterFrame;
};
mc.onReleaseOutside = mc.onRelease;

How it works

The only difference between this code and the constraint to a circle is the content of the MovieClip.onEnterFrame function literal.  Again, the movie clip’s original position is noted in two dynamic properties, arbitrarily named origX and origY.  Again, the MovieClip.onPress, onRelease, and onReleaseOutside events assign and cancel the function responsible for the specialized dragging.  Inside that function, even the angle variable is still recorded via the Math.atan2() method.

This time, however, there is no need for a distance variable; or rather, it could be said that the meaning of distance has changed, because an ellipse features both width and height.  There are two if statements involved, here.  The first evaluates the mouse’s horizontal position with respect to the movie clip’s original position.  Using the same distance formula as last time, this if statement determines whether the mouse is within the horizontal width of an ellipse whose left or right edge is 200 pixels from its center.  If the mouse is within this area, the movie clip is simply placed where the mouse is; otherwise, it is positioned where the edge of the ellipse would be.

This same procedure is repeated for vertical placement in the next if statement.  Notice that the radius portion of the formula is 100, because this ellipse is wider than it is tall.

Leave a Reply