Animate Along a Path

Actionscript:
  1. stage.frameRate = 30;
  2. var pencil:Shape = new Shape();
  3. addChild(pencil);
  4.  
  5. var index:int = 0;
  6. var points:Array = new Array();
  7. var circle:Shape = new Shape();
  8. circle.graphics.beginFill(0x000000);
  9. circle.graphics.drawCircle(0,0, 5);
  10. addChild(circle);
  11.  
  12. stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
  13. stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
  14.  
  15. circle.addEventListener(Event.ENTER_FRAME, onMoveCircle);
  16.  
  17. function onDown(evt:MouseEvent):void {
  18.     pencil.graphics.lineStyle(0,0x000000);
  19.     pencil.graphics.moveTo(mouseX, mouseY);
  20.     stage.addEventListener(MouseEvent.MOUSE_MOVE, onDraw);
  21. }
  22.  
  23. function onUp(evt:MouseEvent):void {
  24.     stage.removeEventListener(MouseEvent.MOUSE_MOVE, onDraw);
  25. }
  26.  
  27. function onDraw(evt:Event):void {
  28.     pencil.graphics.lineTo(mouseX, mouseY);
  29.     points.push(new Point(mouseX, mouseY));
  30. }
  31.  
  32. function onMoveCircle(evt:Event):void {
  33.     if (points.length>0) {
  34.         circle.x += (points[index].x - circle.x) / 4;
  35.         circle.y += (points[index].y - circle.y) / 4;
  36.         index++;
  37.         if (index==points.length) {
  38.             index=0;
  39.         }
  40.     }
  41. }

Wrote this in response to a student question. It causes a circle shape to animate along lines drawn by the user.

This entry was posted in arrays, motion and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. vlad
    Posted January 16, 2009 at 5:38 pm | Permalink

    Thank you. What a great post!
    Is there a way to detect “sudden moves”, let’s say when a circle jumps some minimum distance from one path to another? I thought it would be cool to add some kind of event when it happens to make the animation more dramatic.

  2. Posted January 17, 2009 at 8:07 am | Permalink

    Thanks Vlad. Yeah there is… the next post I wrote after this one is actually about Mouse Velocity… it compares the mouseX and mouseY from the previous enterFrame to the mouseX and mouseY on the current enterFrame… if a sudden movement occurs the x and y differences will be greater… check out this post.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*