Posted By

orazal on 08/29/07


Tagged

math actionscript


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

n00ge
orazal


constrainToArea


 / Published in: ActionScript
 

Useful for draggable clips that should be constrained to an area.

  1. /*
  2. * Checks a clip's position and size and repositions inside an area
  3. *
  4. *@param clip Movieclip to reposition
  5. *@param area An object indication the area that the clip should be constrained to
  6. *@param reposition Boolean indicating if movieclip's position should be modified
  7. *@param hSpacing Horizontal margin from the border
  8. *@param vSpacing Vertical margin from the border
  9. *@returns An object with the x and y values that are inside the area
  10. */
  11. function constrainToArea(clip:MovieClip, area:Object, reposition:Boolean, hSpacing:Number, vSpacing:Number):Array {
  12. if (!hSpacing) {
  13. var hSpacing:Number = 0;
  14. }
  15. if (!vSpacing) {
  16. var vSpacing:Number = 0;
  17. }
  18. var clipPoint:Object = new Object();
  19. clipPoint.x = clip._x;
  20. clipPoint.y = clip._y;
  21. clip._parent.localToGlobal(clipPoint);
  22. // Return same position
  23. var newX = clip._x;
  24. var newY = clip._y;
  25. // Reposition on x
  26. var overX = area.width-(clipPoint.x+clip._width);
  27. if (overX<0) {
  28. newX -= Math.abs(overX)+hSpacing;
  29. }
  30. if (clipPoint.x<0) {
  31. newX += Math.abs(clipPoint.x)+hSpacing;
  32. }
  33. // Reposition on y
  34. var overY = area.height-(clipPoint.y+clip._height);
  35. if (overY<0) {
  36. newY -= Math.abs(overY)+vSpacing;
  37. }
  38. if (clipPoint.y<0) {
  39. newY += Math.abs(clipPoint.y)+vSpacing;
  40. }
  41. if (reposition) {
  42. clip._x = newX;
  43. clip._y = newY;
  44. }
  45. return {x:newX, y:newY};
  46. }

Report this snippet  

You need to login to post a comment.