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

Box2D Magnet

/**
 * Copyright shapevent ( http://wonderfl.net/user/shapevent )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/sdlB
 */

package {
    import flash.display.*;
    import flash.events.*;
    import flash.text.*;
    import com.actionsnippet.qbox.*;
    import Box2D.Common.Math.*;
    
    public class FlashTest extends MovieClip {
        
        private var sim:QuickBox2D;
        private var out:TextField;
        private var big:QuickObject;
        private var little:QuickObject;
        private var dir:b2Vec2;
        public function FlashTest() {
            
            sim = new QuickBox2D(this);
            
            sim.createStageWalls();
            
            big = sim.addCircle({x: 7, y: 7, radius: 3, density: 0});
            
            little = sim.addCircle({x : 3, y: 12, radius: 1, friction:5});
            
            sim.start();
            sim.mouseDrag();
            addEventListener(Event.ENTER_FRAME, onLoop);
            
            out = new TextField();
            out.x = out.y = 50;
            out.border = true;
            out.autoSize = "left";
            addChild(out);
            
            dir = new b2Vec2();
        }
        
        // this is where the magnet code happens:
        
        private function onLoop(evt:Event):void{
            var ang:Number = angle(big, little);
            out.text = String(ang);
            var maxDist:Number = 100;
            
            var intensity:Number = 2;
            var currVel:b2Vec2 = little.body.GetLinearVelocity();
            
            dir.x = currVel.x + intensity * Math.cos(ang);
            dir.y = currVel.y + intensity * Math.sin(ang);
            
            little.body.SetLinearVelocity(dir);
        }
        private function dist(a:QuickObject, b:QuickObject):Number{
          var dx:Number = a.x - b.x;
          var dy:Number = a.y - b.y;
          
          return Math.sqrt(dx * dx + dy * dy);    
        }
        private function angle(a:QuickObject, b:QuickObject):Number{
          var dx:Number = a.x - b.x;
          var dy:Number = a.y - b.y;
          
          return Math.atan2(dy,dx);  
        }
    }
}