Pachinko Dice Prototype

by charles.anifowose forked from パチンコ (diff: 127)
Pachinko Dice Prototype, precursor to iphone app to use as substitute for dice

forked from: パチンコ
♥0 | Line 327 | Modified 2012-06-18 00:10:37 | MIT License
play

ActionScript3 source code

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

// forked from Yukulele's ????
package {
    import Box2D.Common.b2Settings;
    import Box2D.Dynamics.Joints.b2JointEdge;
    import Box2D.Dynamics.Joints.b2MouseJoint;
    import Box2D.Dynamics.Joints.b2MouseJointDef;
    import flash.display.BitmapData;
    import flash.display.DisplayObject;
    import flash.display.Sprite;
    import flash.display.Shape;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    import flash.geom.Matrix;
    import Box2D.Dynamics.*;
    import Box2D.Collision.*;
    import Box2D.Collision.Shapes.*;
    import Box2D.Common.Math.*;
    import net.hires.debug.Stats;
    import flash.utils.getTimer;
    [SWF(backgroundColor=0x000000,frameRate=40,width=467,height=467)]
    public class Main extends Sprite {
        private var the_world:b2World;
        private var timerOld:int;
        private var time_count:Timer = new Timer(50);
        private var mouseJoint:b2MouseJoint; 
        private var mousePVec:b2Vec2 = new b2Vec2();
        private var myBoundaryListener:BoundaryListener = new BoundaryListener();
        private const echelle:Number = 30;
        private const sceneColor:Number= 0xCCCCCC;
        private var mouseJointGraph:Shape = new Shape;
        public function Main() {
            timerOld = getTimer();
            var environment:b2AABB = new b2AABB();
            environment.lowerBound.Set(0-2, -10);
            environment.upperBound.Set(15.5 + 2, 17);
            var gravity:b2Vec2=new b2Vec2(0.0,9.81);
            the_world = new b2World(environment, gravity, true);
            
            var def:b2BodyDef = new b2BodyDef();
            def.position.Set(x, y);
            def.isBullet = true;
            var s:Shape = new Shape();
            var body:b2Body = the_world.CreateBody(def);
            var centerStage:Number
            var middleStage:Number = centerStage = stage.stageWidth/2-10
            
            var debug_draw:b2DebugDraw = new b2DebugDraw();
            var debug_sprite:Sprite = new Sprite();
            addChild(debug_sprite);
            debug_draw.m_sprite=debug_sprite;
            debug_draw.m_drawScale=echelle;
            debug_draw.m_fillAlpha = 0.5;
            debug_draw.m_lineThickness=0;
            debug_draw.m_drawFlags =
                //b2DebugDraw.e_aabbBit|
                //b2DebugDraw.e_centerOfMassBit|
                //b2DebugDraw.e_coreShapeBit|
                b2DebugDraw.e_jointBit|
                //b2DebugDraw.e_obbBit|
                //b2DebugDraw.e_pairBit|
                b2DebugDraw.e_shapeBit|
                0;
            
            the_world.SetDebugDraw(debug_draw);



            
            var knobRadius:Number = 0.3;
            var knobLevels:Number = 8;
            
            for (var i:uint=1; i<=knobLevels; i++){
                var offsetX:Number = - 4*knobRadius*(i+1)/2;
                for (var j:uint=0; j<i; j++){
                    offsetX += (4*knobRadius);
                    createKnob ( middleStage / echelle + offsetX, ((4*knobRadius)*i + 10/echelle), knobRadius);  
                }
            }
            function createKnob(x:Number,y:Number, r:Number):void{
                var cercleDef:b2CircleDef = new b2CircleDef();
                cercleDef.localPosition.Set(x, y);
                cercleDef.radius = r;
                cercleDef.friction = .5;
                cercleDef.restitution = .6;
                body.CreateShape(cercleDef);
                s.graphics.beginFill(sceneColor);
                s.graphics.drawCircle(x*echelle, y*echelle, r * echelle);                
            }
            
            // draw border
            s.graphics.lineStyle(1,sceneColor );
            s.graphics.moveTo(middleStage - knobRadius*echelle, echelle - 2*knobRadius*echelle);
            s.graphics.lineTo(middleStage-(4*knobRadius*knobLevels*0.5*echelle)- knobRadius*echelle, (4*knobRadius*knobLevels  + 2*knobRadius)*echelle );
            
            
             // draw border
            var edgeDef:b2PolygonDef, ln:Array;
            ln = [ [centerStage + 3*knobRadius*echelle, echelle - 2*knobRadius*echelle],
                   [centerStage+(4*knobRadius*knobLevels*0.5*echelle + 3*knobRadius*echelle), (4*knobRadius*knobLevels  + 2*knobRadius)*echelle] ]
            edgeDef = new b2PolygonDef();
            edgeDef.vertexCount = 4;
            
            edgeDef.vertices[3].Set( (ln[1][0])/echelle,ln[1][1]/echelle);
            edgeDef.vertices[2].Set( (ln[1][0]-20)/echelle,ln[1][1]/echelle);
            edgeDef.vertices[1].Set( (ln[0][0]-20)/echelle,ln[0][1]/echelle);
            edgeDef.vertices[0].Set( (ln[0][0])/echelle,(ln[0][1])/echelle);
            
            
            edgeDef.friction = 1;
            edgeDef.restitution = 1;
            edgeDef.density = 1;
            body.CreateShape(edgeDef);
            body.SetMassFromShapes();
            positionner(body);
            
            s.graphics.lineStyle(1,sceneColor );
            s.graphics.moveTo( ln[0][0], ln[0][1] );
            s.graphics.lineTo( ln[1][0], ln[1][1] );         
            
            
               
            

            body.SetUserData(s);
            addChildAt(s, 0);
            positionner(body);
            body.SetMassFromShapes();
            
            ballCount = 0;
            maxBallCount = 100;
            
            the_world.SetBoundaryListener(myBoundaryListener);
            addEventListener(Event.ENTER_FRAME, on_enter_frame);
            time_count.addEventListener(TimerEvent.TIMER, on_time);
            time_count.start();
            var stats:Stats=new Stats({bg:0x5577bb});
            stats.alpha=.5;
            stage.addChild(stats);
            addChild(mouseJointGraph);
            stage.addEventListener(MouseEvent.MOUSE_DOWN, createMouse);
            stage.addEventListener(MouseEvent.MOUSE_UP, destroyMouse);
        }
        private var ballCount:uint, maxBallCount:uint;
        private function on_time(e:Event):void 
        {
            ballCount ++;
            var color:Number;
            if (ballCount > maxBallCount){
                return
            }
            else if (ballCount == int(maxBallCount*.2)){
                creeCercle( (stage.stageWidth/2-10) / echelle , -1, .125, 0xFF0000);
            }
            else{
                creeCercle( (stage.stageWidth/2-10 + 5*Math.random()-2.5) / echelle , -1, .1, 0x000000);
            }

             
            //creeCercle(7.75 + (Math.random() - .5) * 10, -5, Math.random() *.2);
        }
        private var constantRad:Number;
        private function creeCercle(x:Number, y:Number, r:Number, color:Number=0x000000):b2Body
        {
            var def:b2BodyDef = new b2BodyDef();
            def.position.Set(x, y);
            def.isBullet = true;
            var body:b2Body = the_world.CreateBody(def);
            var cercleDef:b2CircleDef = new b2CircleDef();
            cercleDef.radius = r;
            cercleDef.density = 10;
            cercleDef.friction = 1;
            cercleDef.restitution = 0.1
            body.CreateShape(cercleDef);
            body.SetMassFromShapes();
            var s:Shape = new Shape();
            s.graphics.beginFill(color);
            s.graphics.drawCircle(0, 0, r * echelle);
            body.SetUserData(s);
            positionner(body);
            addChildAt(s, 0);
            return(body);
        }
        private function dessiner_polygone(points:Object):Shape
        {
            
            var bd:BitmapData = new BitmapData(2, 2,true);
            var bd2:BitmapData = new BitmapData(2, 2,true);
            var c1:uint = Math.random() * 0xffffff;
            bd.setPixel(0, 0, 0);
            bd.setPixel32(0, 1, c1|0xff000000);
            bd.setPixel32(1, 0, c1|0x88000000);
            bd.setPixel(1, 1, 0);
            var s:Shape=new Shape;
            //s.graphics.lineStyle(2);
            //s.graphics.beginFill(Math.random() * 0xffffff,1);
            //s.graphics.lineBitmapStyle(bd,new Matrix(0.9397,0.3420,-0.3420,0.9397),true,true);
            c1 = Math.random() * 0xffffff;
            bd2.setPixel(0, 0, 0);
            bd2.setPixel32(0, 1, c1|0xff000000);
            bd2.setPixel32(1, 0, c1|0x88000000);
            bd2.setPixel(1, 1, 0);
            s.graphics.beginBitmapFill(bd2,null,true,true);
            //s.graphics.beginBitmapFill(bd2,new Matrix(Math.random()*1.1,Math.random()*1.1,-Math.random()*1.1,Math.random()*1.1),true,true);
            s.graphics.moveTo(points.x[0]*echelle,points.y[0]*echelle);
            for(var i:int=1; i<points.x.length;i++)
            {
                s.graphics.lineTo(points.x[i]*echelle,points.y[i]*echelle);
            }
            //s.graphics.lineTo(points.x[0]*echelle,points.y[0]*echelle);
            s.graphics.endFill();
            return s;

        }
        private var temps:int;
        private function on_enter_frame(e:Event):void {
            temps = getTimer() - timerOld;
            timerOld = getTimer();
            //the_world.Step(temps/1000, 10);
            the_world.Step(stage.frameRate/1000, 10);
            
            myBoundaryListener.lastBodys().forEach(function(elm:b2Body, num:int, vect:Vector.<b2Body>):void {
                var joint:b2JointEdge = elm.GetJointList();
                while(joint)
                {
                    if (joint.joint == mouseJoint)
                        mouseJoint = null;
                    the_world.DestroyJoint(joint.joint);
                    joint = joint.next;
                }
                removeChild(elm.GetUserData());
                the_world.DestroyBody(elm);
            });
            var body:b2Body = the_world.GetBodyList();
            while (body)
            {
                if (body.GetMass() != 0)
                    positionner(body);
                body = body.GetNext();
            }
            if (mouseJoint) {
                
                var mouseXWorldPhys:Number=mouseX/echelle;
                var mouseYWorldPhys:Number=mouseY/echelle;
                var p2:b2Vec2=new b2Vec2(mouseXWorldPhys,mouseYWorldPhys);
                mouseJoint.SetTarget(p2);
                mouseJointGraph.graphics.clear();
                var v1:b2Vec2 = mouseJoint.GetAnchor1().Copy();
                var v2:b2Vec2 = mouseJoint.GetAnchor2();
                mouseJointGraph.graphics.lineStyle(0, 0x00ff00);
                mouseJointGraph.graphics.moveTo(v1.x * echelle, v1.y * echelle);
                mouseJointGraph.graphics.lineTo(v2.x * echelle, v2.y * echelle);
                var cx:Number = (v1.x + v2.x) / 2;
                var cy:Number = (v1.y + v2.y) / 2;
                v1.Subtract(v2);
                var rayon:Number = v1.Length()/2;
                //mouseJointGraph.graphics.lineStyle(rayon*echelle/100, 0x00ff00);
                //mouseJointGraph.graphics.drawCircle(cx*echelle, cy*echelle,rayon*echelle)
                if(mouseJointGraph.parent===null)
                    addChild(mouseJointGraph);
            }
            else if(mouseJointGraph.parent===this)
            {
                removeChild(mouseJointGraph);
            }
        }
        public function createMouse(evt:MouseEvent):void {
            var body:b2Body=GetBodyAtMouse();
            if (body) {
                var mouseJointDef:b2MouseJointDef=new b2MouseJointDef  ;
                mouseJointDef.body1=the_world.GetGroundBody();
                mouseJointDef.body2=body;
                mouseJointDef.target.Set(mouseX/echelle, mouseY/echelle);
                mouseJointDef.maxForce=100;
                mouseJointDef.timeStep=temps/1000;
                mouseJoint=the_world.CreateJoint(mouseJointDef) as b2MouseJoint;
            }
        }
        public function destroyMouse(evt:MouseEvent=null):void {
            if (mouseJoint) {
                the_world.DestroyJoint(mouseJoint);
                mouseJoint=null;
            }
        }
        public function GetBodyAtMouse(includeStatic:Boolean=false):b2Body {
            var mouseXWorldPhys:Number = (mouseX)/echelle;
            var mouseYWorldPhys:Number = (mouseY)/echelle;
            mousePVec.Set(mouseXWorldPhys, mouseYWorldPhys);
            var aabb:b2AABB = new b2AABB();
            aabb.lowerBound.Set(mouseXWorldPhys - 0.001, mouseYWorldPhys - 0.001);
            aabb.upperBound.Set(mouseXWorldPhys + 0.001, mouseYWorldPhys + 0.001);
            var k_maxCount:int=10;
            var shapes:Array = new Array();
            var count:int=the_world.Query(aabb,shapes,k_maxCount);
            var body:b2Body=null;
            for (var i:int = 0; i < count; ++i) {
                if (shapes[i].GetBody().IsStatic()==false||includeStatic) {
                    var tShape:b2Shape=shapes[i] as b2Shape;
                    var inside:Boolean=tShape.TestPoint(tShape.GetBody().GetXForm(),mousePVec);
                    if (inside) {
                        body=tShape.GetBody();
                        break;
                    }
                }
            }
            return body;
        }
        private function positionner(body:b2Body):void
        {
            var graphic:* = body.GetUserData();
            if (!(graphic is DisplayObject))
                return;
            var bodyPosition:b2Vec2= body.GetPosition();
            var bodyRotation:Number = body.GetAngle();

            graphic.rotation=0;
            var m:Matrix=graphic.transform.matrix;

            m.tx = 0;
            m.ty = 0;
            m.rotate(bodyRotation);

            m.tx+=bodyPosition.x*echelle;
            m.ty+=bodyPosition.y*echelle;

            graphic.transform.matrix = m;
        }
    }
}
class BoundaryListener extends Box2D.Dynamics.b2BoundaryListener
{
    import Box2D.Dynamics.b2Body;
    import Box2D.Dynamics.b2World;
    private var bodys:Vector.<b2Body>;
    public function BoundaryListener()
    {
        bodys = new Vector.<b2Body>;
    }
    public override function Violation(body:b2Body):void 
    {
        bodys.push(body);
    }
    public function lastBodys():Vector.<b2Body>
    {
        var bodys2:Vector.<b2Body> = bodys;
        bodys = new Vector.<b2Body>;
        return bodys2;
    }
}
class Actor
{
    
    import Box2D.Dynamics.b2Body;
    import flash.display.DisplayObject;
    import Box2D.Common.Math.b2Vec2;
    import flash.geom.Matrix;public var body:b2Body;
    public var graphic:DisplayObject;
    public static var echelle:Number;
    function Actor(b:b2Body, g:DisplayObject){
        body = b;
        graphic = g;
    }
    public function positionner():void
    {
        // World state position
        var bodyPosition:b2Vec2=body.GetPosition();
        var bodyRotation:Number=body.GetAngle();

        // Sprite rotation based (0,0) correct for size by moving sprite before rotation.
        // ie. rotation about the center of the sprite.
        graphic.rotation=0;// If not, matrix starts wrong.
        var m:Matrix=graphic.transform.matrix;

        m.tx = 0;// - a.graphic.width / 2;
        m.ty = 0;// - a.graphic.height / 2;
        m.rotate(bodyRotation);// Already in radians

        // Now set the position to the world position
        m.tx+=bodyPosition.x*echelle;
        m.ty+=bodyPosition.y*echelle;

        // ...and set the whole thing at once via the matrix.
        // ie. Update the sprite.
        graphic.transform.matrix = m;
    }
}