AS3: Scroller


 / Published in: ActionScript 3
 

This may not be useful to anyone else as is, but I wanted to keep my typical scrolling code somewhere for easy access. This uses TweenMax as well which obviously isn't included. This assumes you have content_mc for the stuff to be scrolled, scrollArrow as your dragger, scrollerTrack as the bar the dragger follows, and contentMask to mask your content within a certain area.

  1. // grab its top position before we scroll anything
  2. private var contentStart:Number = content_mc.landPort.content_mc.y;
  3. private var dragRatio:Number;
  4.  
  5. // add the mouse_down to the scrollArrow and add the mouse_up to the stage
  6. scrollArrow.addEventListener (MouseEvent.MOUSE_DOWN, drag);
  7. this.addEventListener (MouseEvent.MOUSE_UP, dragOff);
  8.  
  9. private function drag (evt:Event):void
  10. {
  11. // figure out how far the content needs to move for each pixel the scrollArrow moves
  12. dragRatio = (content_mc.height-contentMask.height) / (scrollerTrack.height-scrollArrow.height);
  13.  
  14. // define where the scrollArrow can move within
  15. var rectangle:Rectangle = new Rectangle(scrollArrow.x, scrollerTrack.y, 0, scrollerTrack.height-scrollArrow.height);
  16.  
  17. // listen for scrolling and start dragging
  18. this.addEventListener (MouseEvent.MOUSE_MOVE, dragging);
  19. evt.target.startDrag (false, rectangle);
  20. }
  21.  
  22. private function dragging (evt:Event):void
  23. {
  24. // figure out where the content needs to scroll to and tween it
  25. var nextPos:Number = contentStart-((scrollArrow.y-contentStart)*dragRatio);
  26. TweenMax.to(content_mc, .5,{y:nextPos});
  27. }
  28. private function dragOff (evt:Event):void
  29. {
  30. // quit yo draggin
  31. evt.target.stopDrag ();
  32. this.removeEventListener (MouseEvent.MOUSE_MOVE, dragging);
  33. }

Report this snippet  

You need to login to post a comment.