package com.physics { import flash.events.Event; import flash.geom.Point; /** * A mass-spring damper system that can be used to simulate * harmonic oscillations in a physics system. * * @author Eddie * @email eddie@illogictree.com */ public class MassSpring extends Entity { // You can tweak the gravity for your needs private static var GRAVITY:Point = new Point( 0, 40 ); private var _mass:Number; // How heavy is the object private var _friction:Number; // How "tight" is the spring private var _springConst:Number; // Controls the bounciness of the spring private var _basePos:Point = new Point; // Where the system is attached to private var _vel:Point = new Point; // Current velocity of the mass public function MassSpring( mass:Number, friction:Number, springConst:Number ) { _mass = mass; _friction = friction; _springConst = springConst; } public function get basePos():Point { return _basePos; } public function set basePos( position:Point ):void { _basePos = position; } override public function update(e:Event):void { // Uses symplectic method for integration var nextPos:Point = new Point; var nextVel:Point = new Point; nextVel.x = _vel.x + ( 1.0 / _mass ) * ( -_friction * _vel.x - _springConst * ( x - _basePos.x ) + GRAVITY.x * _mass ) * Game.deltaSecs; nextVel.y = _vel.y + ( 1.0 / _mass ) * ( -_friction * _vel.y - _springConst * ( y - _basePos.y ) + GRAVITY.y * _mass ) * Game.deltaSecs; nextPos.x = x + nextVel.x * Game.deltaSecs; nextPos.y = y + nextVel.y * Game.deltaSecs; // Update the current position x = nextPos.x; y = nextPos.y; // Update velocity _vel = nextVel; } } }