Mouse follower code

4 posts

Flag Post

This is a cool example of how to make a MovieClip follow the mouse, and “spring” to the mouse position.

Create a MovieClip on the stage and give it an instance name of ‘ball’

// two-dimensional springing example
// spring to mouse!


var spring:Number = 0.1;
var friction:Number = 0.85;
ball.x = 0;
ball.y = 0;
var vx:Number = 0;
var vy:Number = 0;
onEnterFrame = function() {
var ax:Number = (xmouse – ball.x) * spring;
var ay:Number = (
ymouse – ball.
y) * spring;
vx += ax;
vy += ay;
vx *= friction;
vy *= friction;
ball.
x += vx;
ball.
y += vy;
};

 
Flag Post

Very nice.

Ported it to AS3 as a inner class. Simply instantiate it and add it to the display list.

import flash.display.Sprite;
import flash.events.Event;

class Follower extends Sprite{
   private static const SPRING:Number = .1;
   private static const FRICTION:Number = .85;
   
   private var vx:Number = 0;
   private var vy:Number = 0;
   
   public function Follower():void{
      this.graphics.lineStyle(1);
      this.graphics.beginFill(0x000);
      this.graphics.drawCircle(0,0,10);
      this.graphics.endFill();
      
      this.addEventListener(Event.ENTER_FRAME, onEnterFrame, false, 0 , true);
   }
   
   private function onEnterFrame(e:Event):void{
      if (this.stage != null){
         
         var ax:Number = (this.stage.mouseX - this.x) * SPRING;
         var ay:Number = (this.stage.mouseY - this.y) * SPRING;
                 
         vx += ax;
         vy += ay;
         vx *= FRICTION;
         vy *= FRICTION;
         
         this.x += vx;
         this.y += vy;
      }
   }
}
 
Flag Post

suppish

i extended it a bit, just create a MovieClip in the library and export it for ActionScript with ball as the identifier


var numberOfBalls:Number = 10
var spring:Number = 0.06;
var friction:Number = 0.8;
var mouse:MovieClip = this.createEmptyMovieClip(“mouse_mc” , this.getNextHighestDepth());
var balls:Array = new Array();
balls
0 = mouse;
for(var i:Number = 1 ; i <= numberOfBalls ; i++) {
var _mc:MovieClip = this.attachMovie(“ball” , "ball"+i , this.getNextHighestDepth());
mc.x = 0;
mc.y = 0;
mc.xscale = mc.yscale = 10 + 90 * (1-(i / numberOfBalls))
_mc.vx = 0;
_mc.vy = 0;
_mc.spring = spring;
_mc.friction = friction;
_mc.toFollow = balls[i-1];
mc.onEnterFrame = function() {
var ax:Number = (this.toFollow.x – this.x) * this.spring;
var ay:Number = (this.toFollow._y – this.
y) * this.spring;
this.vx += ax;
this.vy += ay;
this.vx *= this.friction;
this.vy *= this.friction;
this.
x += this.vx;
this.
y += this.vy;
};
balls[i] = _mc;
}
mouse.startDrag(true);

 
Flag Post

That’s actually pretty nice. More elegant than what I usually use.