In case Flash no longer exists; a copy of this site is included in the Flashpoint archive's "ultimate" collection.

Dead Code Preservation :: Archived AS3 works from wonderfl.net

offset spring

Get Adobe Flash player
by majoraze 24 Nov 2010
    Embed
/**
 * Copyright majoraze ( http://wonderfl.net/user/majoraze )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/6Bnd
 */

package {
    import flash.display.Sprite;
    import flash.events.Event;
    
    public class OffsetSpring extends Sprite {
        private var ball:Ball;
        private var spring:Number = .1;
        private var vx:Number = 0;
        private var vy:Number = 0;
        private var friction:Number = 0.9;
        private var springLength:Number = 100; //the value of offset
        
        public function OffsetSpring() {
            init();
        }
        
        private function init():void {
            ball = new Ball(20);
            addChild(ball);
            addEventListener(Event.ENTER_FRAME, onEnterFrame);
        }
        
        private function onEnterFrame(e:Event):void {
            var dx:Number = ball.x - mouseX;
            var dy:Number = ball.y - mouseY;
            var angle:Number = Math.atan2(dy,dx);
            
            var targetX:Number = mouseX + Math.cos(angle) * springLength;
            var targetY:Number = mouseY + Math.sin(angle) * springLength;
            
            vx += (targetX - ball.x) * spring;
            vy += (targetY - ball.y) * spring;
            vx *= friction;
            vy *= friction;
            ball.x += vx;
            ball.y += vy;
            
            graphics.clear();
            graphics.lineStyle(1);
            graphics.moveTo(ball.x, ball.y);
            graphics.lineTo(mouseX, mouseY);
            
        }


    }
}




//ball class

import flash.display.Sprite;

class Ball extends Sprite {
    public var radius:Number;
    private var color:uint;
    public var vx:Number = 0;
    public var vy:Number = 0;    
    
    public function Ball(radius:Number = 40, color:uint = 0xff0000) {
        this.radius = radius;
        this.color = color;
        
        init();
    }
    
    public function init():void {
        graphics.beginFill(color);
        graphics.drawCircle(0,0,radius);
        graphics.endFill()
    }
}