Exemple #1
0
        void InitStackWithWorld(b2World theWorld)
        {
            this.world = theWorld;

            if (TheLevel.SharedLevel.IS_IPAD)
            {
                stackLocationX = 1400;  //base X starting point for the entire stack on the iPad (make further tweaks using the  stackAdjustmentX var in the buildLevel function per level
                stackLocationY = 100; //base Y starting point for the entire stack on the iPad (make further tweaks using the  stackAdjustmentY var in the buildLevel function per level
            }
            else
            {

                stackLocationX = 900;  //base X starting point for the entire stack on the iPhone (make further tweaks using the  stackAdjustmentX var in the buildLevel function per level
                stackLocationY = 35; //base Y starting point for the entire stack on the iPhone (make further tweaks using the  stackAdjustmentY var in the buildLevel function per level
            }

            currentLevel = GameData.SharedData.Level;
            if (currentLevel % 2 == 0)
            {
                BuildLevel2();
            }
            else
            {
                BuildLevel1();
            }
        }
Exemple #2
0
 public MouseTouch(b2World world, RubeBasicLayer layer)
 {
     parent = layer;
     m_world = world;
     b2BodyDef bodyDef = new b2BodyDef();
     m_groundBody = m_world.CreateBody(bodyDef);
 }
Exemple #3
0
        public Enemy(b2World world,
		              CCPoint location,
		              string spriteFileName,
		              bool isTheRotationFixed,
		              bool getsDamageFromGround,
		              bool doesGetDamageFromDamageEnabledStackObjects,
		              int breaksFromHowMuchContact,
		              bool hasDifferentSpritesForDamage,
		              int numberOfFramesToAnimateOnBreak,
		              float density,
		              CreationMethod createHow,
		              int points,
		              BreakEffect simpleScoreVisualFXType )
        {
            InitWithWorld( world,
                           location,
                           spriteFileName,
                           isTheRotationFixed,
                           getsDamageFromGround,
                           doesGetDamageFromDamageEnabledStackObjects,
                           breaksFromHowMuchContact,
                           hasDifferentSpritesForDamage,
                           numberOfFramesToAnimateOnBreak,
                           density,
                           createHow,
                           points,
                           simpleScoreVisualFXType );
        }
        void InitPhysics()
        {
            var gravity = new b2Vec2(0.0f, -10.0f);
            world = new b2World(gravity);

            world.SetAllowSleeping(true);
            world.SetContinuousPhysics(true);

            var def = new b2BodyDef();
            def.allowSleep = true;
            def.position = b2Vec2.Zero;
            def.type = b2BodyType.b2_staticBody;

            b2Body groundBody = world.CreateBody(def);
            groundBody.SetActive(true);

            b2EdgeShape groundBox = new b2EdgeShape();
            groundBox.Set(b2Vec2.Zero, new b2Vec2(900, 100));

            b2FixtureDef fd = new b2FixtureDef();
            fd.friction = 0.3f;
            fd.restitution = 0.1f;
            fd.shape = groundBox;

            groundBody.CreateFixture(fd);
        }
Exemple #5
0
        public JumpPad(b2Vec2 JumpImpuls, CCPoint Position, b2World gameWorld)
        {
            this.Texture = new CCTexture2D ("jumppad");
            this.Scale = SpriteScale;
            this.Position = Position;
            this.IsAntialiased = false;

            jumpImpuls = JumpImpuls;
            totalJumps = 0;

            //box2d
            b2BodyDef jumpPadDef = new b2BodyDef ();
            jumpPadDef.type = b2BodyType.b2_kinematicBody;
            jumpPadDef.position = new b2Vec2 ((Position.X + this.ScaledContentSize.Width/2)/PhysicsHandler.pixelPerMeter, (Position.Y + this.ScaledContentSize.Height/4) / PhysicsHandler.pixelPerMeter);
            JumpPadBody = gameWorld.CreateBody (jumpPadDef);

            b2PolygonShape jumpPadShape = new b2PolygonShape ();
            jumpPadShape.SetAsBox ((float)this.ScaledContentSize.Width / PhysicsHandler.pixelPerMeter / 2, (float)this.ScaledContentSize.Height / PhysicsHandler.pixelPerMeter / 4);// /4 weil die hitbox nur die hälfte der textur ist

            b2FixtureDef jumpPadFixture = new b2FixtureDef ();
            jumpPadFixture.shape = jumpPadShape;
            jumpPadFixture.density = 0.0f; //Dichte
            jumpPadFixture.restitution = 0f; //Rückprall
            jumpPadFixture.friction = 0f;
            jumpPadFixture.userData = WorldFixtureData.jumppad;
            JumpPadBody.CreateFixture (jumpPadFixture);
            //
        }
		private void InitWithWorld( b2World world, CCPoint location, string spriteFileName)
		{
			this.theWorld = world;
			this.initialLocation = location;
			this.spriteImageName = spriteFileName;
			CreateGround();
		}
		public BreakEffect  SimpleScoreVisualFX { get; set; } //defined in Constants.cs

		public StackObject (b2World world, 
		                    CCPoint location,
		                    string spriteFileName,
		                    bool breaksOnGround,
		                    bool breaksFromNinja,
		                    bool hasAnimatedBreakFrames,
		                    bool damagesEnemy,
		                    float density,
		                    CreationMethod createHow,
		                    int angleChange,
		                    bool makeImmovable,
		                    int points,
		                    BreakEffect simpleScoreVisualFXType)
		{
			InitWithWorld(world, 
			              location, 
			              spriteFileName, 
			              breaksOnGround,
			              breaksFromNinja,
			              hasAnimatedBreakFrames,
			              damagesEnemy,
			              density,
			              createHow,
			              angleChange,
			              makeImmovable,
			              points,
			              simpleScoreVisualFXType);
		}
        void InitWithWorld(b2World world,
                            CCPoint location,
                            string spriteFileName,
                            bool isTheRotationFixed,
                            bool getsDamageFromGround,
                            bool doesGetDamageFromDamageEnabledStackObjects,
                            int breaksFromHowMuchContact,
                            bool hasDifferentSpritesForDamage,
                            int numberOfFramesToAnimateOnBreak,
                            float density,
                            CreationMethod createHow,
                            int points,
                            BreakEffect simpleScoreVisualFXType)
        {
            this.theWorld = world;
            this.initialLocation = location;
            this.baseImageName = spriteFileName;
            this.spriteImageName = String.Format("{0}", baseImageName);

            this.DamagesFromGroundContact = getsDamageFromGround; // does the ground break / damage the enemy

            this.damageLevel = 0; //starts at 0, if breaksAfterHowMuchContact also equals 0 then the enemy will break on first/next contact
            this.breaksAfterHowMuchContact = breaksFromHowMuchContact; //contact must be made this many times before breaking, or if set to 0, the enemy will break on first/next contact 
            this.differentSpritesForDamage = hasDifferentSpritesForDamage; //will progress through damage frames if this is YES, for example,  enemy_damage1.png, enemy_damage2.png

            this.currentFrame = 0;
            this.framesToAnimateOnBreak = numberOfFramesToAnimateOnBreak;  //will animate through breaks frames if this is more than 0, for example,  enemy_break0001.png, enemy_break0002.png


            this.theDensity = density;
            this.shapeCreationMethod = createHow;

            this.isRotationFixed = isTheRotationFixed;

            this.PointValue = points;
            this.SimpleScoreVisualFX = simpleScoreVisualFXType;

            this.DamagesFromDamageEnabledStackObjects = doesGetDamageFromDamageEnabledStackObjects;


            if (damageLevel == breaksAfterHowMuchContact)
            {
                BreaksOnNextDamage = true;
            }
            else
            {
                BreaksOnNextDamage = false; //duh

            }


            CreateEnemy();


        }
		private void InitWithWorld (b2World world, CCPoint location, string baseFileName)
		{
			
			theWorld = world;
			initialLocation = location;
			baseImageName = baseFileName;
			
			
			//later we use initialLocation.x 
			
			CreateNinja();
		}
Exemple #10
0
        // This method should undo anything that was done by the loadWorld and afterLoadProcessing
        // methods, and return to a state where loadWorld can safely be called again.
        public void clear()
        {
            if (m_world != null)
            {
                Console.WriteLine("Deleting Box2D world");
                m_world = null;
            }

            if (m_debugDraw != null)
                m_debugDraw = null;

            //m_world = NULL;
            //m_mouseJoint = NULL;
            // m_mouseJointGroundBody = null;
        }
        protected void CreateBodyWithSpriteAndFixture(b2World world, b2BodyDef bodyDef,
                                                       b2FixtureDef fixtureDef, string spriteName)
        {
            // this is the meat of our class, it creates (OR recreates) the body in the world with the body definition, fixture definition and sprite name

            RemoveBody(); //if remove the body if it already exists
            RemoveSprite(); //if remove the sprite if it already exists

            sprite = new CCSprite(spriteName);
            AddChild(sprite);

            body = world.CreateBody(bodyDef);
            body.UserData = this;

            if (fixtureDef != null)
                body.CreateFixture(fixtureDef);
        }
Exemple #12
0
        public GameScene(Game game)
        {
            this.game = game;
            // ��ʼ��world
            b2Vec2 gravity = new b2Vec2(0f, -20f);
            world = new b2World(gravity);
            world.AllowSleep = false;
            InitBack();
            AddBarLayer();

            InitScore();
            AddGround();
            AddBird();
            world.SetContactListener(new BirdContactListener(this, (CCSprite)(birdBody.UserData)));
            this.schedule(tick);

            SimpleAudioEngine.sharedEngine().playBackgroundMusic(@"musics/background", true);
        }
Exemple #13
0
        public void Initialize(float mapSizeWidth, Character Character, CCTileMapLayer physicsLayer, CCTileMap physicsMap, Container gameContainer)
        {
            mapSizeWidth /= pixelPerMeter;
            gameWorld = new b2World (new b2Vec2 (0, -9.8f));
            gameWorld.AllowSleep = false;

            //definiert den MainCharacter
            Character.createPhysicsBody (gameWorld);
            defineGround (mapSizeWidth);

            createBox2DWorldByLayer (physicsLayer, physicsMap);

            debugDrawer = new DebugDraw ();
            gameWorld.SetDebugDraw (debugDrawer);
            debugDrawer.AppendFlags (b2DrawFlags.e_shapeBit);

            collusionSensor = new CollusionSensor (gameContainer);
            gameWorld.SetContactListener (collusionSensor);
        }
Exemple #14
0
        public void SetJson(string fullpath)
        {
            Console.WriteLine("Full path is: %s", fullpath);

            Nb2dJson json = new Nb2dJson();
            StringBuilder tmp = new StringBuilder();
            m_world = json.ReadFromFile(fullpath, tmp);

            if (m_world != null)
            {
                Console.WriteLine("Loaded JSON ok");
                m_world.SetDebugDraw(m_debugDraw);

                b2BodyDef bodyDef = new b2BodyDef();
                m_groundBody = m_world.CreateBody(bodyDef);
            }
            else
                Console.WriteLine(tmp); //if this warning bothers you, turn off "Typecheck calls to printf/scanf" in the project build settings

        }
Exemple #15
0
        public Mouse()
        {
            //m_destructionListener = new DestructionListener();
            m_debugDraw = new CCBox2dDraw("fonts/arial-16");

            b2Vec2 gravity = new b2Vec2();
            gravity.Set(500, 500);
           
            m_world = new b2World(gravity);

            
            m_world.SetAllowSleeping(false);
            m_world.SetContinuousPhysics(true);


            m_world.SetDebugDraw(m_debugDraw);
            m_debugDraw.AppendFlags(b2DrawFlags.e_shapeBit | b2DrawFlags.e_aabbBit | b2DrawFlags.e_centerOfMassBit | b2DrawFlags.e_jointBit | b2DrawFlags.e_pairBit);

            m_world.SetContinuousPhysics(true);
            m_world.SetWarmStarting(true);
        }
Exemple #16
0
        public virtual void Refilter()
        {
            if (m_body == null)
            {
                return;
            }

            // Flag associated contacts for filtering.
            b2ContactEdge edge = m_body.ContactList;

            while (edge != null)
            {
                b2Contact contact  = edge.Contact;
                b2Fixture fixtureA = contact.GetFixtureA();
                b2Fixture fixtureB = contact.GetFixtureB();
                if (fixtureA == this || fixtureB == this)
                {
                    contact.FlagForFiltering();
                }

                edge = edge.Next;
            }

            b2World world = m_body.World;

            if (world == null)
            {
                return;
            }

            // Touch each proxy so that new pairs may be created
            b2BroadPhase broadPhase = world.ContactManager.BroadPhase;

            for (int i = 0; i < m_proxyCount; ++i)
            {
                broadPhase.TouchProxy(m_proxies[i].proxyId);
            }
        }
        public BoxProp(
               b2World b2world,

             double[] size,
             double[] position

            )
        {
            /*
            static rectangle shaped prop
     
                pars:
                size - array [width, height]
                position - array [x, y], in world meters, of center
            */
            this.size = size;

            //initialize body
            var bdef = new b2BodyDef();
            bdef.position = new b2Vec2(position[0], position[1]);
            bdef.angle = 0;
            bdef.fixedRotation = true;
            this.body = b2world.CreateBody(bdef);

            //initialize shape
            var fixdef = new b2FixtureDef();

            var shape = new b2PolygonShape();
            fixdef.shape = shape;

            shape.SetAsBox(this.size[0] / 2, this.size[1] / 2);

            fixdef.restitution = 0.4; //positively bouncy!



            this.body.CreateFixture(fixdef);
        }
		void InitWithWorld(b2World world, 
		                   CCPoint location,
		                   string spriteFileName,
		                   bool breaksOnGround,
		                   bool breaksFromNinja,
		                   bool hasAnimatedBreakFrames,
		                   bool damagesEnemy,
		                   float density,
		                   CreationMethod createHow,
		                   int angleChange,
		                   bool makeImmovable,
		                   int points,
		                   BreakEffect simpleScoreVisualFXType)
		{
			this.theWorld = world;
			this.initialLocation = location;
			this.baseImageName = spriteFileName;
			this.spriteImageName =  String.Format("{0}", baseImageName);
			
			this.IsBreaksOnGroundContact = breaksOnGround; 
			this.IsBreaksOnNinjaContact = breaksFromNinja; 
			this.addedAnimatedBreakFrames = hasAnimatedBreakFrames;
			this.IsCanDamageEnemy = damagesEnemy;
			this.theDensity = density;
			this.shapeCreationMethod = createHow;
			this.angle = angleChange;
			this.IsStatic = makeImmovable;
			
			this.currentFrame = 0;
			this.framesToAnimate = 10;
			
			this.PointValue = points ;
			this.SimpleScoreVisualFX = simpleScoreVisualFXType;
			
			CreateObject();
				
		}
        public ApplicationSprite()
        {

            #region AtInitializeConsoleFormWriter

            var w = new __OutWriter();
            var o = Console.Out;
            var __reentry = false;

            var __buffer = new StringBuilder();

            w.AtWrite =
                x =>
                {
                    __buffer.Append(x);
                };

            w.AtWriteLine =
                x =>
                {
                    __buffer.AppendLine(x);
                };

            Console.SetOut(w);

            this.AtInitializeConsoleFormWriter = (
                Action<string> Console_Write,
                Action<string> Console_WriteLine
            ) =>
            {

                try
                {


                    w.AtWrite =
                        x =>
                        {
                            o.Write(x);

                            if (!__reentry)
                            {
                                __reentry = true;
                                Console_Write(x);
                                __reentry = false;
                            }
                        };

                    w.AtWriteLine =
                        x =>
                        {
                            o.WriteLine(x);

                            if (!__reentry)
                            {
                                __reentry = true;
                                Console_WriteLine(x);
                                __reentry = false;
                            }
                        };

                    Console.WriteLine("flash Console.WriteLine should now appear in JavaScript form!");
                    Console.WriteLine(__buffer.ToString());
                }
                catch
                {

                }
            };
            #endregion




            var SCALE = 15;      //how many pixels in a meter
            var WIDTH_M = DefaultWidth / SCALE; //world width in meters. for this example, world is as large as the screen
            var HEIGHT_M = DefaultHeight / SCALE; //world height in meters

            //initialize font to draw text with
            //var font=new gamejs.font.Font('16px Sans-serif');

            //key bindings
            //var BINDINGS={accelerate:gamejs.event.K_UP, 
            //              brake:gamejs.event.K_DOWN,      
            //              steer_left:gamejs.event.K_LEFT, 
            //               steer_right:gamejs.event.K_RIGHT}; 









            //initialize display
            //var display = gamejs.display.setMode([WIDTH_PX, HEIGHT_PX]);

            //SET UP B2WORLD
            var b2world = new b2World(new b2Vec2(0, 0), false);

            //set up box2d debug draw to draw the bodies for us.
            //in a real game, car will propably be drawn as a sprite rotated by the car's angle
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(this);
            debugDraw.SetDrawScale(SCALE);
            debugDraw.SetFillAlpha(0.5);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
            b2world.SetDebugDraw(debugDraw);

            var wheels = new[] { 
                //top left
                new Wheel(b2world: b2world, x :-1,  y :-1.2,  width :0.4,  length :0.8,  revolving :true,  powered :true),

                //top right
                new Wheel(b2world: b2world, x :1,  y :-1.2,  width :0.4,  length :0.8,  revolving :true,  powered :true),

                //back left
                new Wheel(b2world: b2world, x :-1,  y :1.2,  width :0.4,  length :0.8,  revolving :false,  powered :false),

                //back right
                new Wheel(b2world: b2world, x :1,  y :1.2,  width :0.4,  length :0.8,  revolving :false,  powered :false),
            };
            Func<double, double, double[]> ff = (a, b) => { return new double[] { a, b }; };

            ////initialize car
            var car = new Car(
                b2world: b2world,
                width: 2,
                length: 4,
                position: ff(10, 10),
                angle: 180,
                power: 60,
                max_steer_angle: 20,
                max_speed: 60,
                wheels: wheels
            );



            //initialize some props to bounce against
            var props = new List<BoxProp>();


            //outer walls
            props.Add(new BoxProp(b2world, size: ff(WIDTH_M, 1), position: ff(WIDTH_M / 2, 0.5)));
            props.Add(new BoxProp(b2world, size: ff(1, HEIGHT_M - 2), position: ff(0.5, HEIGHT_M / 2)));
            props.Add(new BoxProp(b2world, size: ff(WIDTH_M, 1), position: ff(WIDTH_M / 2, HEIGHT_M - 0.5)));
            props.Add(new BoxProp(b2world, size: ff(1, HEIGHT_M - 2), position: ff(WIDTH_M - 0.5, HEIGHT_M / 2)));

            //pen in the center
            var center = new double[] { WIDTH_M / 2, HEIGHT_M / 2 };
            props.Add(new BoxProp(b2world, size: ff(1, 6), position: ff(center[0] - 3, center[1])));
            props.Add(new BoxProp(b2world, size: ff(1, 6), position: ff(center[0] + 3, center[1])));
            props.Add(new BoxProp(b2world, size: ff(5, 1), position: ff(center[0], center[1] + 2.5)));

            var frameid = 0;

            var KEYS_DOWN = new Dictionary<Keys, bool> { 
            
                { Keys.Left, false },
                { Keys.Up, false },
                { Keys.Right, false },
                { Keys.Down, false },
            }; //keep track of what keys are held down by the player


            this.stage.keyDown +=
                e =>
                {
                    Console.WriteLine("keyDown " + new { e.keyCode });
                    KEYS_DOWN[(Keys)e.keyCode] = true;
                };

            this.stage.keyUp +=
               e =>
               {
                   Console.WriteLine("keyUp " + new { e.keyCode });
                   KEYS_DOWN[(Keys)e.keyCode] = false;
               };


            #region tick
            Action<double> tick = (msDuration) =>
            {
                frameid++;

                //if (frameid > 1)
                //    return;

                //Console.WriteLine(new { frameid });
                //GAME LOOP

                //handle events. Key status (depressed or no) is tracked in via KEYS_DOWN associative array
                //gamejs.event.get().forEach(function(event){
                //    //key press
                //    if (event.type === gamejs.event.KEY_DOWN) KEYS_DOWN[event.key] = true;
                //    //key release
                //    else if (event.type === gamejs.event.KEY_UP) KEYS_DOWN[event.key] = false;           
                //});

                //set car controls according to player input
                if (KEYS_DOWN[Keys.Up])
                {
                    car.accelerate = ACC_ACCELERATE;
                }
                else if (KEYS_DOWN[Keys.Down])
                {
                    car.accelerate = ACC_BRAKE;
                }
                else
                {
                    car.accelerate = ACC_NONE;
                }

                if (KEYS_DOWN[Keys.Right])
                {
                    car.steer = STEER_RIGHT;
                }
                else if (KEYS_DOWN[Keys.Left])
                {
                    car.steer = STEER_LEFT;
                }
                else
                {
                    car.steer = STEER_NONE;
                }

                ////update car
                car.update(msDuration);

                //update physics world
                b2world.Step(msDuration / 1000.0, 10, 8);

                //clear applied forces, so they don't stack from each update
                b2world.ClearForces();

                //fill background
                //gamejs.draw.rect(display, '#FFFFFF', new gamejs.Rect([0, 0], [WIDTH_PX, HEIGHT_PX]),0)

                //let box2d draw it's bodies
                b2world.DrawDebugData();

                //fps and car speed display
                //display.blit(font.render('FPS: '+parseInt((1000)/msDuration)), [25, 25]);
                //display.blit(font.render('SPEED: '+parseInt(Math.ceil(car.getSpeedKMH()))+' km/h'), [25, 55]);
                //Console.WriteLine(new { frameid } + " done!");
            };

            ////gamejs.time.fpsCallback(tick, this, 60);
            var sw = new Stopwatch();
            sw.Start();

            this.enterFrame +=
                delegate
                {
                    tick(sw.ElapsedMilliseconds);
                    sw.Restart();
                };
            #endregion

        }
            public Car(
                b2World b2world,

                double width,
                double length,
                double[] position,
                double angle,
                double power,
                double max_steer_angle,
                double max_speed,
                Wheel[] wheels
                )
            {
                //        /*
                //        pars is an object with possible attributes:

                //        width - width of the car in meters
                //        length - length of the car in meters
                //        position - starting position of the car, array [x, y] in meters
                //        angle - starting angle of the car, degrees
                //        max_steer_angle - maximum angle the wheels turn when steering, degrees
                //        max_speed       - maximum speed of the car, km/h
                //        power - engine force, in newtons, that is applied to EACH powered wheel
                //        wheels - wheel definitions: [{x, y, rotatable, powered}}, ...] where
                //                 x is wheel position in meters relative to car body center
                //                 y is wheel position in meters relative to car body center
                //                 revolving - boolean, does this turn rotate when steering?
                //                 powered - is force applied to this wheel when accelerating/braking?
                //        */



                //        this.max_steer_angle=pars.max_steer_angle;
                //        this.max_speed=pars.max_speed;
                //        this.power=pars.power;
                var wheel_angle = 0.0;//keep track of current wheel angle relative to car.
                //                           //when steering left/right, angle will be decreased/increased gradually over 200ms to prevent jerkyness.

                //initialize body
                var def = new b2BodyDef();
                def.type = b2Body.b2_dynamicBody;
                def.position = new b2Vec2(position[0], position[1]);
                def.angle = angle.DegreesToRadians();
                def.linearDamping = 0.15;  //gradually reduces velocity, makes the car reduce speed slowly if neither accelerator nor brake is pressed
                def.bullet = true; //dedicates more time to collision detection - car travelling at high speeds at low framerates otherwise might teleport through obstacles.
                def.angularDamping = 0.3;

                this.body = b2world.CreateBody(def);

                //initialize shape
                var fixdef = new b2FixtureDef();
                fixdef.density = 1.0;
                fixdef.friction = 0.3; //friction when rubbing agaisnt other shapes
                fixdef.restitution = 0.4;  //amount of force feedback when hitting something. >0 makes the car bounce off, it's fun!

                var fixdef_shape = new b2PolygonShape();

                fixdef.shape = fixdef_shape;
                fixdef_shape.SetAsBox(width / 2, length / 2);
                body.CreateFixture(fixdef);

                //initialize wheels
                foreach (var item in wheels)
                {
                    item.Initialize(this);
                }

                //return array of wheels that turn when steering
                IEnumerable<Wheel> getRevolvingWheels = from w in wheels where w.revolving select w;
                //        //return array of powered wheels
                IEnumerable<Wheel> getPoweredWheels = from w in wheels where w.powered select w;

                #region setSpeed
                Action<double> setSpeed = (speed) =>
                {
                    /*
                    speed - speed in kilometers per hour
                    */
                    var velocity0 = this.body.GetLinearVelocity();

                    //Console.WriteLine("car setSpeed velocity0 " + new { velocity0.x, velocity0.y });

                    var velocity2 = vectors.unit(new[] { velocity0.x, velocity0.y });

                    //Console.WriteLine("car setSpeed velocity2 " + new { x = velocity2[0], y = velocity2[1] });
                    var velocity = new b2Vec2(
                        velocity2[0] * ((speed * 1000.0) / 3600.0),
                        velocity2[1] * ((speed * 1000.0) / 3600.0)
                    );

                    //Console.WriteLine("car setSpeed SetLinearVelocity " + new { velocity.x, velocity.y });
                    this.body.SetLinearVelocity(velocity);

                };
                #endregion


                #region getSpeedKMH
                Func<double> getSpeedKMH = delegate
                {
                    var velocity = this.body.GetLinearVelocity();
                    var len = vectors.len(new double[] { velocity.x, velocity.y });
                    return (len / 1000.0) * 3600.0;
                };
                #endregion

                #region getLocalVelocity
                Func<double[]> getLocalVelocity = delegate
                {
                    /*
                    returns car's velocity vector relative to the car
                    */
                    var retv = this.body.GetLocalVector(this.body.GetLinearVelocityFromLocalPoint(new b2Vec2(0, 0)));
                    return new double[] { retv.x, retv.y };
                };
                #endregion



                #region update
                this.update = (msDuration) =>
                {


                    #region 1. KILL SIDEWAYS VELOCITY

                    //kill sideways velocity for all wheels
                    for (var i = 0; i < wheels.Length; i++)
                    {
                        wheels[i].killSidewaysVelocity();
                    }
                    #endregion



                    #region 2. SET WHEEL ANGLE

                    //calculate the change in wheel's angle for this update, assuming the wheel will reach is maximum angle from zero in 200 ms
                    var incr = (max_steer_angle / 200.0) * msDuration;

                    if (steer == STEER_RIGHT)
                    {
                        wheel_angle = Math.Min(Math.Max(wheel_angle, 0) + incr, max_steer_angle); //increment angle without going over max steer
                    }
                    else if (steer == STEER_LEFT)
                    {
                        wheel_angle = Math.Max(Math.Min(wheel_angle, 0) - incr, -max_steer_angle); //decrement angle without going over max steer
                    }
                    else
                    {
                        wheel_angle = 0;
                    }

                    //update revolving wheels
                    getRevolvingWheels.WithEach(
                        w => w.setAngle(wheel_angle)
                    );

                    #endregion


                    #region 3. APPLY FORCE TO WHEELS
                    var base_vect = new double[2]; //vector pointing in the direction force will be applied to a wheel ; relative to the wheel.

                    //if accelerator is pressed down and speed limit has not been reached, go forwards
                    var lessthanlimit = (getSpeedKMH() < max_speed);
                    var flag1 = (accelerate == ACC_ACCELERATE) && lessthanlimit;
                    if (flag1)
                    {
                        base_vect = new double[] { 0, -1 };
                    }
                    else if (accelerate == ACC_BRAKE)
                    {
                        //braking, but still moving forwards - increased force
                        if (getLocalVelocity()[1] < 0)
                        {
                            base_vect = new double[] { 0, 1.3 };
                        }
                        //going in reverse - less force
                        else
                        {
                            base_vect = new double[] { 0, 0.7 };
                        }
                    }
                    else
                    {
                        base_vect[0] = 0;
                        base_vect[1] = 0;
                    }

                    //multiply by engine power, which gives us a force vector relative to the wheel
                    var fvect = new double[] { 
                        power * base_vect[0], 
                        power * base_vect[1] 
                    };

                    //apply force to each wheel



                    getPoweredWheels.WithEachIndex(
                        (w, i) =>
                        {
                            var wp = w.body.GetWorldCenter();
                            var wf = w.body.GetWorldVector(new b2Vec2(fvect[0], fvect[1]));

                            //Console.WriteLine("getPoweredWheels ApplyForce #" + i);
                            w.body.ApplyForce(wf, wp);
                        }
                    );




                    //if going very slow, stop - to prevent endless sliding
                    var veryslow = (getSpeedKMH() < 4);
                    var flag2 = veryslow && (accelerate == ACC_NONE);
                    if (flag2)
                    {
                        //Console.WriteLine("setSpeed 0");
                        setSpeed(0);
                    }
                    #endregion


                };
                #endregion

            }
Exemple #21
0
		public StartPlatform (b2World world, CCPoint location, string spriteFileName)
		{
			InitWithWorld(world, location, spriteFileName);
		}
		protected override void AddedToScene()
		{
			base.AddedToScene();

			layerInstance = this;

			//get screen size
			screenSize = Window.WindowSizeInPixels; //CCDirector::sharedDirector()->getWinSize();



			//INITIAL VARIABLES.... (D O N T    E D I T )

			// enable touches
#if XBOX || OUYA
            TouchEnabled = false;
            GamePadEnabled = true;
#else
			//TouchEnabled = true;

			CCEventListenerTouchAllAtOnce tListener = new CCEventListenerTouchAllAtOnce();

			tListener.OnTouchesBegan = TouchesBegan;
			//tListener.OnTouchesCancelled = TouchesCancelled;
			tListener.OnTouchesEnded = TouchesEnded;
			tListener.OnTouchesMoved = TouchesMoved;

			AddEventListener(tListener, this);

#endif


			// enable accelerometer
			//AccelerometerEnabled = false;

#if iPHONE || iOS
			IS_IPAD = MonoTouch.UIKit.UIDevice.CurrentDevice.UserInterfaceIdiom 
				== MonoTouch.UIKit.UIUserInterfaceIdiom.Pad;

			IS_RETINA = MonoTouch.UIKit.UIScreen.MainScreen.Bounds.Height 
				* MonoTouch.UIKit.UIScreen.MainScreen.Scale >= 1136;
#endif
#if WINDOWS || MACOS || MONOMAC || LINUX || OUYA || XBOX
			IS_IPAD = true;
			IS_RETINA = true;
#endif

			IS_IPHONE = !IS_IPAD;

			// ask director for the window size
			screenWidth = (int)screenSize.Width;
			screenHeight = (int)screenSize.Height;

			throwInProgress = false; //is a throw currently in progress, as in, is a ninja in midair (mostly used to prevent tossing two ninjas, one right after another)
			areWeInTheStartingPosition = true;  //is the world back at 0 on the X axis (if yes, then we can put a ninja in the sling)

			throwCount = 0;
			dotTotalOnOddNumberedTurn = 0;
			dotTotalOnEvenNumberedTurn = 0;

			currentLevel = GameData.SharedData.Level;  // use currentLevel =  0 for testing new shapes, will call [self buildLevelWithAllShapes];

			pointTotalThisRound = 0;
			pointsToPassLevel = GameData.SharedData.PointsToPassLevel;
			bonusPerExtraNinja = GameData.SharedData.BonusPerExtraNinja;

			CCLog.Log(string.Format("The level is {0}, you need {1} to move up a level", currentLevel, pointsToPassLevel));

			//PREFERENCE VARIABLES....

			openWithMenuInsteadOfGame = false; // start with the menu opening the game

			continuePanningScreenOnFingerRelease = true; // if the screen panning is midway between either the sling or targets, when you release your finger the screen will continue panning the last direction it moved (jumpy on iPhone if set to NO)
			reverseHowFingerPansScreen = false; //switch to yes to reverse. 
			topRightTouchEnablesDebugMode = true;  //SET TO NO IN FINAL BUILD
			useImagesForPointScoreLabels = true; //IF NO, means you use Marker Felt text for scores

			//set up background art

			backgroundLayerClouds = new CCSprite(GameData.SharedData.BackgroundCloudsFileName);  // will return the background clouds file for a particular level
			AddChild(backgroundLayerClouds, Constants.DepthClouds);

			backgroundLayerHills = new CCSprite(GameData.SharedData.BackgroundHillsFileName);  // will return the background hills file for a particular level
			AddChild(backgroundLayerHills, Constants.DepthHills);
			backgroundLayerHills.ScaleX = 1.05f;

			slingShotFront = new CCSprite("slingshot_front");
			AddChild(slingShotFront, Constants.DepthSlingShotFront);

			strapFront = new CCSprite("strap");
			AddChild(strapFront, Constants.DepthStrapFront);


			strapBack = new CCSprite("strapBack");
			AddChild(strapBack, Constants.DepthStrapBack);

			strapEmpty = new CCSprite("strapEmpty");
			AddChild(strapEmpty, Constants.DepthStrapBack);


			strapBack.Visible = false;  //visible only when stretching
			strapFront.Visible = false; //visible only when stretching



			//setup positions and variables for iPad devices or iPhones

			if (IS_IPAD)
			{
				areWeOnTheIPad = true;

				//vars 

				maxStretchOfSlingShot = 75; //best to leave as is, since this value ties in closely to the image size of strap.png. (should be 1/4 the size of the source image)
				multipyThrowPower = 1; // fine tune how powerful the sling shot is. Range is probably best between .5 to 1.5, currently for the iPad 1.0 is good

				worldMaxHorizontalShift = -(screenWidth);  // This determines how far the user can slide left or right to see the entire board. Always a negative number. 
				maxScaleDownValue = 1.0f; //dont change
				scaleAmount = 0; // increment to change the scale of the entire world when panning  
				initialPanAmount = 30; //how fast the screen pan starts
				extraAmountOnPanBack = 10; // I like a faster pan back. Adding a bit more
				adjustY = 0; // best to leave at 0 for iPad (moves the world down when panning)

				//background stuff

				backgroundLayerClouds.Position = new CCPoint(screenWidth, screenHeight / 2);
				backgroundLayerHills.Position = new CCPoint(screenWidth, screenHeight / 2);

				if (!IS_RETINA)
				{


					//non retina adjustment


				}
				else
				{

					//retina adjustment

					backgroundLayerClouds.Scale = 2.0f;
					backgroundLayerHills.Scale = 2.0f;
				}


				menuStartPosition = new CCPoint(130, screenSize.Height - 24);
				currentScoreLabelStartPosition = new CCPoint(200, screenSize.Height - 60);
				highScoreLabelStartPosition = new CCPoint(200, screenSize.Height - 80);

				fontSizeForScore = 22;

				//ground plane and platform

				groundPlaneStartPosition = new CCPoint(screenWidth, 50);
				platformStartPosition = new CCPoint(340, 190);

				//sling shot
				slingShotCenterPosition = new CCPoint(370, 255);

				slingShotFront.Position = new CCPoint(374, 240);
				strapFront.Position = new CCPoint(slingShotCenterPosition.X, slingShotCenterPosition.Y);
				strapBack.Position = new CCPoint(slingShotCenterPosition.X + 33, slingShotCenterPosition.Y - 10);
				strapEmpty.Position = new CCPoint(378, 235);

				//ninja

				ninjaStartPosition1 = new CCPoint(380, 250);
				ninjaStartPosition2 = new CCPoint(300, 155);
				ninjaStartPosition3 = new CCPoint(260, 155);
				ninjaStartPosition4 = new CCPoint(200, 120);
				ninjaStartPosition5 = new CCPoint(160, 120);

			}

			else if (IS_IPHONE)
			{
				//CCLOG (@"this is an iphone");

				areWeOnTheIPad = false;

				//vars 
				maxStretchOfSlingShot = 75; //best to leave as is, since this value ties in closely to the image size of strap.png. (should be 1/4 the size of the source image)
				multipyThrowPower = 1.0f; // fine tune how powerful the sling shot is. Range is probably best between .5 to 1.5, and a little goes a long way

				worldMaxHorizontalShift = -(screenWidth); // This determines how far the user can slide left or right to see the entire board. Always a negative number
				maxScaleDownValue = 0.65f; //range should probably be between 0.75 and 1.0;
				scaleAmount = .01f; // increment to change the scale of the entire world when panning
				adjustY = -34;

				initialPanAmount = 20; //how fast the screen pan starts
				extraAmountOnPanBack = 0; // best to leave at 0 on iPhone

				//background stuff



				if (!IS_RETINA)
				{

					//non retina adjustment

					backgroundLayerClouds.Position = new CCPoint(screenWidth, 192);
					backgroundLayerClouds.Scale = .7f;
					backgroundLayerHills.Position = new CCPoint(screenWidth, 245);
					backgroundLayerHills.Scale = .7f;

				}
				else
				{

					//retina adjustment

					backgroundLayerClouds.Position = new CCPoint(screenWidth, 192);
					backgroundLayerClouds.Scale = 1.7f;
					backgroundLayerHills.Position = new CCPoint(screenWidth, 265);
					backgroundLayerHills.Scale = 1.7f;
				}



				menuStartPosition = new CCPoint(70, screenSize.Height - 17);
				currentScoreLabelStartPosition = new CCPoint(140, screenSize.Height - 50); //score label
				highScoreLabelStartPosition = new CCPoint(140, screenSize.Height - 70);
				fontSizeForScore = 18;

				//ground plane and platform

				groundPlaneStartPosition = new CCPoint(screenWidth, -25);
				platformStartPosition = new CCPoint(130, 120);

				//sling shot

				slingShotCenterPosition = new CCPoint(160, 185);
				slingShotFront.Position = new CCPoint(164, 170);
				strapFront.Position = new CCPoint(slingShotCenterPosition.X, slingShotCenterPosition.Y);
				strapBack.Position = new CCPoint(slingShotCenterPosition.X + 33, slingShotCenterPosition.Y - 10);
				strapEmpty.Position = new CCPoint(168, 163);

				//ninja

				ninjaStartPosition1 = new CCPoint(170, 175);
				ninjaStartPosition2 = new CCPoint(110, 82);
				ninjaStartPosition3 = new CCPoint(65, 82);
				ninjaStartPosition4 = new CCPoint(90, 65);
				ninjaStartPosition5 = new CCPoint(43, 65);



			}

			SetUpParticleSystemSun();

			CCMenuItemImage button1 = new CCMenuItemImage("gameMenu", "gameMenu", ShowMenu);

			MenuButton = new CCMenu(button1);
			MenuButton.Position = menuStartPosition;
			AddChild(MenuButton, Constants.DepthScore);



			// assign CCPoints to keep track of the starting positions of objects that move relative to the entire layer.

			hillsLayerStartPosition = backgroundLayerHills.Position;
			cloudLayerStartPosition = backgroundLayerClouds.Position;

			// Define the gravity vector.

			yAxisGravity = -9.81f;

			b2Vec2 gravity = b2Vec2.Zero;
			gravity.Set(0.0f, yAxisGravity);


			// Construct a world object, which will hold and simulate the rigid bodies.
			world = new b2World(gravity);

			world.AllowSleep = false;

			world.SetContinuousPhysics(true);

			//EnableDebugMode();


			// Define the ground body.
			var groundBodyDef = new b2BodyDef();  // Make sure we call 
			groundBodyDef.position.Set(0, 0); // bottom-left corner

			// Call the body factory which allocates memory for the ground body
			// from a pool and creates the ground box shape (also from a pool).
			// The body is also added to the world.
			b2Body groundBody = world.CreateBody(groundBodyDef);

			// Define the ground box shape.
			b2EdgeShape groundBox = new b2EdgeShape();

			int worldMaxWidth = screenWidth * 4; //If you ever want the BOX2D world width to be more than it is then increase this  (currently, this should be plenty of extra space)
			int worldMaxHeight = screenHeight * 3; //If you ever want the BOX2D world height to be more  than it is then increase this (currently, this should be plenty of extra space)

			// bottom
			groundBox.Set(new b2Vec2(-4, 0), new b2Vec2(worldMaxWidth / Constants.PTM_RATIO, 0));
			groundBody.CreateFixture(groundBox, 0);

			// top
			groundBox.Set(new b2Vec2(-4, worldMaxHeight / Constants.PTM_RATIO), new b2Vec2(worldMaxWidth / Constants.PTM_RATIO, worldMaxHeight / Constants.PTM_RATIO));
			groundBody.CreateFixture(groundBox, 0);

			// left
			groundBox.Set(new b2Vec2(-4, worldMaxHeight / Constants.PTM_RATIO), new b2Vec2(-4, 0));
			groundBody.CreateFixture(groundBox, 0);

			// right
			groundBox.Set(new b2Vec2(worldMaxWidth / Constants.PTM_RATIO, worldMaxHeight / Constants.PTM_RATIO), new b2Vec2(worldMaxWidth / Constants.PTM_RATIO, 0));
			groundBody.CreateFixture(groundBox, 0);

			//Contact listener 
			contactListener = new ContactListener();
			world.SetContactListener(contactListener);

			//Set up the ground plane

			theGroundPlane = new GroundPlane(world, groundPlaneStartPosition, GameData.SharedData.GroundPlaneFileName);
			AddChild(theGroundPlane, Constants.DepthFloor);


			//Set up the starting platform

			thePlatform = new StartPlatform(world, platformStartPosition, "platform");
			AddChild(thePlatform, Constants.DepthPlatform);

			//Set up ninjas

			ninjaBeingThrown = 1; //always starts at 1 (first ninja, then second ninja, and so on) 
			ninjasToTossThisLevel = GameData.SharedData.NumberOfNinjasToTossThisLevel;  //total number of ninjas to toss for this level



			ninja1 = new Ninja(world, ninjaStartPosition1, @"ninja");
			AddChild(ninja1, Constants.DepthNinjas);

			currentBodyNode = ninja1;

			currentBodyNode.SpriteInSlingState();

			if (ninjasToTossThisLevel >= 2)
			{

				ninja2 = new Ninja(world, ninjaStartPosition2, @"ninjaRed");
				AddChild(ninja2, Constants.DepthNinjas);
				ninja2.SpriteInStandingState();

			}
			if (ninjasToTossThisLevel >= 3)
			{

				ninja3 = new Ninja(world, ninjaStartPosition3, @"ninjaBlue");
				AddChild(ninja3, Constants.DepthNinjas);
				ninja3.SpriteInStandingState();
			}
			if (ninjasToTossThisLevel >= 4)
			{

				ninja4 = new Ninja(world, ninjaStartPosition4, @"ninjaBrown");
				AddChild(ninja4, Constants.DepthNinjas);
				ninja4.SpriteInStandingState();
			}
			if (ninjasToTossThisLevel >= 5)
			{

				ninja5 = new Ninja(world, ninjaStartPosition5, @"ninjaGreen");
				AddChild(ninja5, Constants.DepthNinjas);
				ninja5.SpriteInStandingState();
			}

			//Build the Stack. 

			stack = new TheStack(world);
			AddChild(stack, Constants.DepthStack);


			//give the stack a moment to drop, then switches every pieces to static (locks it into position, until the first slingshot)...
			ScheduleOnce(SwitchAllStackObjectsToStatic, 1.0f);

			currentScoreLabel = new CCLabelTtf(String.Format("{0}: Needed", pointsToPassLevel), "MarkerFelt", fontSizeForScore);
			AddChild(currentScoreLabel, Constants.DepthScore);
			currentScoreLabel.Color = new CCColor3B(255, 255, 255);
			currentScoreLabel.Position = currentScoreLabelStartPosition;
			currentScoreLabel.AnchorPoint = new CCPoint(1, .5f);
			// HighScoreForLevel
			highScoreLabel = new CCLabelTtf(String.Format("High Score: {0}", GameData.SharedData.HighScoreForLevel), "MarkerFelt", fontSizeForScore);
			AddChild(highScoreLabel, Constants.DepthScore);
			highScoreLabel.Color = new CCColor3B(255, 255, 255);

			highScoreLabel.Position = currentScoreLabel.Position - new CCPoint(0, highScoreLabel.ContentSize.Height);// highScoreLabelStartPosition;
			highScoreLabel.AnchorPoint = new CCPoint(1, .5f);
			highScoreLabelStartPosition = highScoreLabel.Position;


			var levelString = string.Format("Level: {0}", currentLevel);
			ShowBoardMessage(levelString);

			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log("/////////////////////////////////////////////////////");
			CCLog.Log("/////////////////////////////////////////////////////");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log("The art and animation in this template is copyright CartoonSmart LLC");
			CCLog.Log("You must make significant changes to the art before submitting your game to the App Store");
			CCLog.Log("Please create your own characters, backgrounds, etc and spend the time to make the game look totally unique");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log("The Video guide for this template is at https://vimeo.com/cartoonsmart/angryninjasguide  ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log(" ");
			CCLog.Log("/////////////////////////////////////////////////////");
			CCLog.Log("/////////////////////////////////////////////////////");
			CCLog.Log(" ");
			CCLog.Log(" ");




			GameSounds.SharedGameSounds.IntroTag();

			if (GameData.SharedData.Level == 1)
			{

				GameSounds.SharedGameSounds.PlayBackgroundMusic(AmbientFXSounds.Frogs);

			}
			else
			{

				GameSounds.SharedGameSounds.PlayBackgroundMusic(AmbientFXSounds.Insects);
			}

			if (GameData.SharedData.FirstRunEver && openWithMenuInsteadOfGame)
			{
				CCLog.Log("First run ever");
				Schedule(ShowMenuFromSelector, 2f);
				GameData.SharedData.FirstRunEver = false;
			}

			// Always do this last.
			this.Schedule(Tick);
		}
		public GroundPlane (b2World world, CCPoint location, string spriteFileName )
		{
			InitWithWorld(world, location, spriteFileName);
		}
Exemple #24
0
        public Test()
        {
            m_destructionListener = new DestructionListener();
            m_debugDraw = new CCBox2dDraw("fonts/arial-12", 1);

            b2Vec2 gravity = new b2Vec2();
            gravity.Set(0.0f, -10.0f);
            m_world = new b2World(gravity);
            m_bomb = null;
            m_textLine = 30;
            m_mouseJoint = null;
            m_pointCount = 0;

            m_destructionListener.test = this;
            m_world.SetDestructionListener(m_destructionListener);
            m_world.SetContactListener(this);
            m_world.SetDebugDraw(m_debugDraw);
            m_world.SetContinuousPhysics(true);
            m_world.SetWarmStarting(true);

            m_bombSpawning = false;

            m_stepCount = 0;

            b2BodyDef bodyDef = new b2BodyDef();
            m_groundBody = m_world.CreateBody(bodyDef);
        }
        void InitPhysics()
        {
            CCSize s = Layer.VisibleBoundsWorldspace.Size;

            var gravity = new b2Vec2 (0.0f, -10.0f);
            world = new b2World (gravity);

            world.SetAllowSleeping (true);
            world.SetContinuousPhysics (true);

            var def = new b2BodyDef ();
            def.allowSleep = true;
            def.position = b2Vec2.Zero;
            def.type = b2BodyType.b2_staticBody;
            b2Body groundBody = world.CreateBody (def);
            groundBody.SetActive (true);

            b2EdgeShape groundBox = new b2EdgeShape ();
            groundBox.Set (b2Vec2.Zero, new b2Vec2 (s.Width / PTM_RATIO, 0));
            b2FixtureDef fd = new b2FixtureDef ();
            fd.shape = groundBox;
            groundBody.CreateFixture (fd);
        }
Exemple #26
0
        private void InitB2World()
        {
            world = new Box2D.Dynamics.b2World(new Box2D.Common.b2Vec2(0, -100));
            world.SetContactListener(new Myb2Listener());
            world.SetAllowSleeping(true);
            world.SetContinuousPhysics(true);
            // Call the body factory which allocates memory for the ground body
            // from a pool and creates the ground box shape (also from a pool).
            // The body is also added to the world.
            def            = new b2BodyDef();
            def.allowSleep = true;
            def.position   = b2Vec2.Zero;
            def.type       = b2BodyType.b2_staticBody;
            b2Body groundBody = world.CreateBody(def);

            groundBody.SetActive(true);

            // Define the ground box shape.

            // bottom
            b2EdgeShape groundBox = new b2EdgeShape();

            groundBox.Set(b2Vec2.Zero, new b2Vec2(Resources.DisplayMetrics.WidthPixels, 0));
            b2FixtureDef fd = new b2FixtureDef();

            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // top
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, Resources.DisplayMetrics.HeightPixels), new b2Vec2(Resources.DisplayMetrics.WidthPixels, Resources.DisplayMetrics.HeightPixels));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // left
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, Resources.DisplayMetrics.HeightPixels), b2Vec2.Zero);
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // right
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(Resources.DisplayMetrics.WidthPixels, Resources.DisplayMetrics.HeightPixels), new b2Vec2(Resources.DisplayMetrics.WidthPixels, 0));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            //
            bodydef          = new b2BodyDef();
            bodydef.active   = true;
            bodydef.position = new b2Vec2(100, 100);
            bodydef.type     = b2BodyType.b2_dynamicBody;
            b2Body buttonBody = world.CreateBody(bodydef);

            buttonBody.SetActive(true);

            var shape = new b2EdgeShape();

            shape.Set(new b2Vec2(100, 100), new b2Vec2(150, 100));
            buttonBody.CreateFixture(new b2FixtureDef()
            {
                density = 10,
                shape   = shape,
            });
        }
Exemple #27
0
        public b2Body(b2BodyDef bd, b2World world)
        {
            BodyFlags = 0;

            if (bd.bullet)
            {
                BodyFlags |= b2BodyFlags.e_bulletFlag;
            }
            if (bd.fixedRotation)
            {
                BodyFlags |= b2BodyFlags.e_fixedRotationFlag;
            }
            if (bd.allowSleep)
            {
                BodyFlags |= b2BodyFlags.e_autoSleepFlag;
            }
            if (bd.awake)
            {
                BodyFlags |= b2BodyFlags.e_awakeFlag;
            }
            if (bd.active)
            {
                BodyFlags |= b2BodyFlags.e_activeFlag;
            }

            World = world;

            Transform.p = bd.position;
            Transform.q.Set(bd.angle);

            Sweep.localCenter.SetZero();
            Sweep.c0     = Transform.p;
            Sweep.c      = Transform.p;
            Sweep.a0     = bd.angle;
            Sweep.a      = bd.angle;
            Sweep.alpha0 = 0.0f;

            JointList   = null;
            ContactList = null;
            Prev        = null;
            Next        = null;

            m_linearVelocity  = bd.linearVelocity;
            m_angularVelocity = bd.angularVelocity;

            LinearDamping  = bd.linearDamping;
            AngularDamping = bd.angularDamping;
            GravityScale   = bd.gravityScale;

            Force.SetZero();
            Torque = 0.0f;

            SleepTime = 0.0f;

            BodyType = bd.type;

            if (BodyType == b2BodyType.b2_dynamicBody)
            {
                Mass         = 1.0f;
                InvertedMass = 1.0f;
            }
            else
            {
                Mass         = 0.0f;
                InvertedMass = 0.0f;
            }

            m_I       = 0.0f;
            InvertedI = 0.0f;

            UserData = bd.userData;

            FixtureList  = null;
            FixtureCount = 0;
        }
Exemple #28
0
        private void initPhysics()
        {
            CCSize s = CCDirector.SharedDirector.WinSize;

            var gravity = new b2Vec2(0.0f, -10.0f);
            _world = new b2World(gravity);
            float debugWidth = s.Width / PTM_RATIO * 2f;
            float debugHeight = s.Height / PTM_RATIO * 2f;
            CCDraw debugDraw = new CCDraw(new b2Vec2(debugWidth / 2f + 10, s.Height - debugHeight - 10), 2);
            debugDraw.AppendFlags(b2DrawFlags.e_shapeBit);
            _world.SetDebugDraw(debugDraw);
            _world.SetAllowSleeping(true);
            _world.SetContinuousPhysics(true);

            //m_debugDraw = new GLESDebugDraw( PTM_RATIO );
            //world->SetDebugDraw(m_debugDraw);

            //uint32 flags = 0;
            //flags += b2Draw::e_shapeBit;
            //        flags += b2Draw::e_jointBit;
            //        flags += b2Draw::e_aabbBit;
            //        flags += b2Draw::e_pairBit;
            //        flags += b2Draw::e_centerOfMassBit;
            //m_debugDraw->SetFlags(flags);


            // Call the body factory which allocates memory for the ground body
            // from a pool and creates the ground box shape (also from a pool).
            // The body is also added to the world.
            b2BodyDef def = b2BodyDef.Create();
            def.allowSleep = true;
            def.position = b2Vec2.Zero;
            def.type = b2BodyType.b2_staticBody;
            b2Body groundBody = _world.CreateBody(def);
            groundBody.SetActive(true);

            // Define the ground box shape.

            // bottom
            b2EdgeShape groundBox = new b2EdgeShape();
            groundBox.Set(b2Vec2.Zero, new b2Vec2(s.Width / PTM_RATIO, 0));
            b2FixtureDef fd = b2FixtureDef.Create();
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // top
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, s.Height / PTM_RATIO), new b2Vec2(s.Width / PTM_RATIO, s.Height / PTM_RATIO));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // left
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, s.Height / PTM_RATIO), b2Vec2.Zero);
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // right
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(s.Width / PTM_RATIO, s.Height / PTM_RATIO), new b2Vec2(s.Width / PTM_RATIO, 0));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // _world.Dump();
        }
        // http://blog.allanbishop.com/box2d-2-1a-tutorial-part-1/

        public ApplicationSprite()
        {

            _world = new b2World(new b2Vec2(0, 10), true);

            var groundBodyDef = new b2BodyDef();
            groundBodyDef.position.Set(SWF_HALF_WIDTH / PIXELS_TO_METRE,
                          SWF_HEIGHT / PIXELS_TO_METRE - 20 / PIXELS_TO_METRE);

            var groundBody = _world.CreateBody(groundBodyDef);

            var groundBox = new b2PolygonShape();
            groundBox.SetAsBox(SWF_HALF_WIDTH / PIXELS_TO_METRE,
                           20 / PIXELS_TO_METRE);

            var groundFixtureDef = new b2FixtureDef();
            groundFixtureDef.shape = groundBox;
            groundFixtureDef.density = 1;
            groundFixtureDef.friction = 1;
            groundBody.CreateFixture(groundFixtureDef);

            var bodyDef = new b2BodyDef();
            bodyDef.type = b2Body.b2_dynamicBody;
            bodyDef.position.Set(SWF_HALF_WIDTH / PIXELS_TO_METRE, 4);
            var body = _world.CreateBody(bodyDef);

            var dynamicBox = new b2PolygonShape();
            dynamicBox.SetAsBox(1, 1);

            var fixtureDef = new b2FixtureDef();
            fixtureDef.shape = dynamicBox;
            fixtureDef.density = 1;
            fixtureDef.friction = 0.3;

            body.CreateFixture(fixtureDef);

            var debugSprite = new Sprite();
            addChild(debugSprite);
            var debugDraw = new b2DebugDraw();
            debugDraw.SetSprite(debugSprite);
            debugDraw.SetDrawScale(PIXELS_TO_METRE);
            debugDraw.SetLineThickness(1.0);
            debugDraw.SetAlpha(1);
            debugDraw.SetFillAlpha(0.4);
            debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
            _world.SetDebugDraw(debugDraw);


            // Add event for main loop

            this.stage.enterFrame +=
                delegate
                {
                    var timeStep = 1 / 30.0;
                    var velocityIterations = 6;
                    var positionIterations = 2;

                    _world.Step(timeStep, velocityIterations, positionIterations);
                    _world.ClearForces();
                    _world.DrawDebugData();

                };


        }
Exemple #30
0
        protected b2Transform m_xf = b2Transform.Default; // the body origin transform

        #endregion Fields

        #region Constructors

        public b2Body(b2BodyDef bd, b2World world)
        {
            m_flags = 0;

            if (bd.bullet)
            {
                m_flags |= b2BodyFlags.e_bulletFlag;
            }
            if (bd.fixedRotation)
            {
                m_flags |= b2BodyFlags.e_fixedRotationFlag;
            }
            if (bd.allowSleep)
            {
                m_flags |= b2BodyFlags.e_autoSleepFlag;
            }
            if (bd.awake)
            {
                m_flags |= b2BodyFlags.e_awakeFlag;
            }
            if (bd.active)
            {
                m_flags |= b2BodyFlags.e_activeFlag;
            }

            m_world = world;

            m_xf.p = bd.position;
            m_xf.q.Set(bd.angle);

            Sweep.localCenter.SetZero();
            Sweep.c0 = m_xf.p;
            Sweep.c = m_xf.p;
            Sweep.a0 = bd.angle;
            Sweep.a = bd.angle;
            Sweep.alpha0 = 0.0f;

            m_jointList = null;
            m_contactList = null;
            Prev = null;
            Next = null;

            m_linearVelocity = bd.linearVelocity;
            m_angularVelocity = bd.angularVelocity;

            m_linearDamping = bd.linearDamping;
            m_angularDamping = bd.angularDamping;
            m_gravityScale = bd.gravityScale;

            m_force.SetZero();
            m_torque = 0.0f;

            m_sleepTime = 0.0f;

            m_type = bd.type;

            if (m_type == b2BodyType.b2_dynamicBody)
            {
                m_mass = 1.0f;
                m_invMass = 1.0f;
            }
            else
            {
                m_mass = 0.0f;
                m_invMass = 0.0f;
            }

            m_I = 0.0f;
            m_invI = 0.0f;

            m_userData = bd.userData;

            m_fixtureList = null;
            m_fixtureCount = 0;
        }
Exemple #31
0
        public b2Body(b2BodyDef bd, b2World world)
        {
            m_flags = 0;

            if (bd.bullet)
            {
                m_flags |= b2BodyFlags.e_bulletFlag;
            }
            if (bd.fixedRotation)
            {
                m_flags |= b2BodyFlags.e_fixedRotationFlag;
            }
            if (bd.allowSleep)
            {
                m_flags |= b2BodyFlags.e_autoSleepFlag;
            }
            if (bd.awake)
            {
                m_flags |= b2BodyFlags.e_awakeFlag;
            }
            if (bd.active)
            {
                m_flags |= b2BodyFlags.e_activeFlag;
            }

            m_world = world;

            m_xf.p = bd.position;
            m_xf.q.Set(bd.angle);

            Sweep.localCenter.SetZero();
            Sweep.c0     = m_xf.p;
            Sweep.c      = m_xf.p;
            Sweep.a0     = bd.angle;
            Sweep.a      = bd.angle;
            Sweep.alpha0 = 0.0f;

            m_jointList   = null;
            m_contactList = null;
            Prev          = null;
            Next          = null;

            m_linearVelocity  = bd.linearVelocity;
            m_angularVelocity = bd.angularVelocity;

            m_linearDamping  = bd.linearDamping;
            m_angularDamping = bd.angularDamping;
            m_gravityScale   = bd.gravityScale;

            m_force.SetZero();
            m_torque = 0.0f;

            m_sleepTime = 0.0f;

            m_type = bd.type;

            if (m_type == b2BodyType.b2_dynamicBody)
            {
                m_mass    = 1.0f;
                m_invMass = 1.0f;
            }
            else
            {
                m_mass    = 0.0f;
                m_invMass = 0.0f;
            }

            m_I    = 0.0f;
            m_invI = 0.0f;

            m_userData = bd.userData;

            m_fixtureList  = null;
            m_fixtureCount = 0;
        }
            public Wheel(
                b2World b2world,

                double x,
                double y,
                double width,
                double length,
                bool revolving,
                bool powered
                )
            {
                this.revolving = revolving;
                this.powered = powered;

                this.Initialize = car =>
                {

                    /*
                    wheel object 

                    pars:

                    car - car this wheel belongs to
                    x - horizontal position in meters relative to car's center
                    y - vertical position in meters relative to car's center
                    width - width in meters
                    length - length in meters
                    revolving - does this wheel revolve when steering?
                    powered - is this wheel powered?
                    */

                    var position = new double[] { x, y };
                    //this.car=pars.car;
                    //this.revolving=pars.revolving;
                    //this.powered=pars.powered;

                    //initialize body
                    var def = new b2BodyDef();
                    def.type = b2Body.b2_dynamicBody;
                    def.position = car.body.GetWorldPoint(new b2Vec2(position[0], position[1]));
                    def.angle = car.body.GetAngle();
                    this.body = b2world.CreateBody(def);

                    //initialize shape
                    var fixdef = new b2FixtureDef();
                    fixdef.density = 1;
                    fixdef.isSensor = true; //wheel does not participate in collision calculations: resulting complications are unnecessary

                    var fixdef_shape = new b2PolygonShape();

                    fixdef.shape = fixdef_shape;
                    fixdef_shape.SetAsBox(width / 2, length / 2);
                    body.CreateFixture(fixdef);

                    var jointdef = new b2RevoluteJointDef();

                    //create joint to connect wheel to body
                    if (revolving)
                    {
                        jointdef.Initialize(car.body, body, body.GetWorldCenter());
                        jointdef.enableMotor = false; //we'll be controlling the wheel's angle manually
                    }
                    else
                    {
                        jointdef.Initialize(car.body, body, body.GetWorldCenter()
                            //, new b2Vec2(1, 0)
                            );
                        jointdef.enableLimit = true;


                        //jointdef.lowerTranslation = 0;
                        //jointdef.upperTranslation = 0;
                    }
                    b2world.CreateJoint(jointdef);

                    #region setAngle
                    this.setAngle =
                        (angle) =>
                        {
                            /*
                            angle - wheel angle relative to car, in degrees
                            */
                            body.SetAngle(car.body.GetAngle() + angle.DegreesToRadians());
                        };
                    #endregion


                    #region getLocalVelocity
                    Func<double[]> getLocalVelocity = delegate
                    {
                        /*returns get velocity vector relative to car
                        */
                        var res = car.body.GetLocalVector(car.body.GetLinearVelocityFromLocalPoint(new b2Vec2(position[0], position[1])));
                        return new double[] { res.x, res.y };
                    };
                    #endregion



                    #region getDirectionVector
                    Func<double[]> getDirectionVector = delegate
                    {
                        /*
                        returns a world unit vector pointing in the direction this wheel is moving
                        */

                        if (getLocalVelocity()[1] > 0)
                            return vectors.rotate(new double[] { 0, 1 }, body.GetAngle());
                        else
                            return vectors.rotate(new double[] { 0, -1 }, body.GetAngle());
                    };
                    #endregion


                    #region getKillVelocityVector
                    Func<double[]> getKillVelocityVector = delegate
                    {
                        /*
                        substracts sideways velocity from this wheel's velocity vector and returns the remaining front-facing velocity vector
                        */
                        var velocity = body.GetLinearVelocity();
                        var sideways_axis = getDirectionVector();
                        var dotprod = vectors.dot(new[] { velocity.x, velocity.y }, sideways_axis);
                        return new double[] { sideways_axis[0] * dotprod, sideways_axis[1] * dotprod };
                    };
                    #endregion

                    #region killSidewaysVelocity
                    this.killSidewaysVelocity = delegate
                    {
                        /*
                        removes all sideways velocity from this wheels velocity
                        */
                        var kv = getKillVelocityVector();

                        body.SetLinearVelocity(new b2Vec2(kv[0], kv[1]));

                    };
                    #endregion
                };

            }
 public TheStack(b2World theWorld)
 {
     InitStackWithWorld(theWorld);
 }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="world"></param>
        /// <param name="ptm"></param>
        public override void CreatePhysicsBody(b2World world, int ptm)
        {
            base.CreatePhysicsBody(world, ptm);
            SetVelocity(InitialVelocityX, InitialVelocityY);

            Ghost.Cleanup();
            Ghost.PositionX = PositionX;
            Ghost.PositionY = PositionY;
            Ghost.DrawRect(new CCRect(0, 0,  Width, Height), new CCColor4B(0, 0, 0, 50));
        }