Example #1
0
 public MouseTouch(b2World world, RubeBasicLayer layer)
 {
     parent = layer;
     m_world = world;
     b2BodyDef bodyDef = new b2BodyDef();
     m_groundBody = m_world.CreateBody(bodyDef);
 }
        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);
        }
Example #3
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);
            //
        }
        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);
        }
Example #5
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

        }
Example #6
0
        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);
        }
Example #7
0
        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);
        }
Example #8
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();
        }
Example #9
0
        /// <summary>
        /// Attempts to load the world from the .json file given by getFilename.
        /// If successful, the method afterLoadProcessing will also be called,
        /// to allow subclasses to do something extra while the b2dJson information
        /// is still available.
        /// </summary>
        private void LoadWorld()
        {
            Clear();

            m_debugDraw = new CCBox2dDraw(DEFAULT_FONT);

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

            string fullpath = GetFilename();

            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_touch = new MouseTouch(m_world, this);

                m_touch.m_mouseJointGroundBody = m_world.CreateBody(bodyDef);

                AfterLoadProcessing(json);
            }
            else
                Console.WriteLine(tmp); //if this warning bothers you, turn off "Typecheck calls to printf/scanf" in the project build settings
        }
Example #10
0
        static void Main(string[] args)
        {
            var gravity = new b2Vec2(0.0f, -10.0f);
            b2World _world = new b2World(gravity);
            _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.
            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.
            float width = 100f, height = 100f;
            // bottom
            b2EdgeShape groundBox = new b2EdgeShape();
            groundBox.Set(b2Vec2.Zero, new b2Vec2(width, 0));
            b2FixtureDef fd = b2FixtureDef.Create();
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            // top
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, height), new b2Vec2(width, height));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

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

            // right
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(width, height), new b2Vec2(width, 0));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            _world.Dump();

            Console.WriteLine("Enter the number of bodies you want to run?");
            string s = Console.ReadLine();
            Random ran = new Random();
            for (int i = 0; i < int.Parse(s); i++)
            {
                def = b2BodyDef.Create();
                def.position = new b2Vec2(width * (float)ran.NextDouble(), height * (float)ran.NextDouble());
                def.type = b2BodyType.b2_dynamicBody;
                b2Body body = _world.CreateBody(def);
                // Define another box shape for our dynamic body.
                var dynamicBox = new b2PolygonShape();
                dynamicBox.SetAsBox(.5f, .5f); //These are mid points for our 1m box

                // Define the dynamic body fixture.
                fd = b2FixtureDef.Create();
                fd.shape = dynamicBox;
                fd.density = 1f;
                fd.friction = 0.3f;
                b2Fixture fixture = body.CreateFixture(fd);
            }

            int iter = 0;
            for (float dt = 0f; dt < 26f; )
            {
                Update(_world, dt);
                dt += 1f / 30f;
                iter++;
                if (iter == 30)
                {
                    Dump(_world);
                    iter = 0;
                }
            }

            Console.WriteLine("hit <enter> to exit");
            Console.ReadLine();

            Dump(_world);
        }
            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
                };

            }
Example #12
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="world"></param>
        public virtual void CreatePhysicsBody(b2World world, int ptm)
        {
            PtmRatio = ptm;

            PhysicsBodyDef = new b2BodyDef();
            PhysicsBodyDef.type = BodyType;
            PhysicsBodyDef.position = new b2Vec2(GetPointToMeter(InitialPositionX), GetPointToMeter(InitialPositionY));
            PhysicsBodyDef.fixedRotation = FixedRotation;
            PhysicsBodyDef.gravityScale = GravityScale;
            PhysicsBodyDef.linearDamping = LinearDamping;
            PhysicsBodyDef.bullet = Bullet;

            PhysicsBody = world.CreateBody(PhysicsBodyDef);
            PhysicsBody.Mass = Mass;
            PhysicsBody.ResetMassData();

            var fixtureDef = new b2FixtureDef();
            fixtureDef.shape = CreatePhysicsShape();
            fixtureDef.density = Density;
            fixtureDef.friction = Friction;

            PhysicsBodyFixture = PhysicsBody.CreateFixture(fixtureDef);
        }
        private void AddShape(b2World world, CCPoint position)
        {
            b2Vec2 positionVec = new b2Vec2(position.X, position.Y);

            var box = new CCPhysicsSprite("hd/images/cloud", IntroLayer.PTM_RATIO);
            box.Position = position;

            var def = new b2BodyDef();
            def.position = new b2Vec2(positionVec.x / IntroLayer.PTM_RATIO, positionVec.y / IntroLayer.PTM_RATIO);
            def.linearVelocity = new b2Vec2(0.0f, -1.0f);
            def.type = b2BodyType.b2_dynamicBody;
            b2Body body = world.CreateBody(def);

            // Polygon Shape
            //var shape = new b2PolygonShape();
            //shape.SetAsBox(50f / IntroLayer.PTM_RATIO, 50f / IntroLayer.PTM_RATIO);

            // Circle Shape
            var shape = new b2CircleShape();
            shape.Radius = 50f / IntroLayer.PTM_RATIO;

            var fd = new b2FixtureDef();
            fd.shape = shape;
            fd.density = 1f;
            fd.restitution = 0f;
            fd.friction = 0.2f;
            body.CreateFixture(fd);

            box.PhysicsBody = body;

            sprites.Add(box);
            AddChild(box);
        }
Example #14
0
        static void SetupWorld(bool setupGround)
        {
            var gravity = new b2Vec2(0.0f, -10.0f);
            _world = new b2World(gravity);
            _world.SetAllowSleeping(true);
            _world.SetContinuousPhysics(true);
            _world.SetSubStepping(true);
            _world.SetWarmStarting(true);
            _world.SetDestructionListener(new Destructo());
            _world.SetContactListener(new Contacto());
            if (!setupGround)
            {
                return;
            }
            // 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);

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

            // top
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(0, height), new b2Vec2(width, height));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

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

            // right
            groundBox = new b2EdgeShape();
            groundBox.Set(new b2Vec2(width, height), new b2Vec2(width, 0));
            fd.shape = groundBox;
            groundBody.CreateFixture(fd);

            _world.Dump();
        }
Example #15
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);
        }
        // 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();

                };


        }
Example #17
0
        public b2Body createPhysicsBody(b2World bodyWorld)
        {
            //definiert den physikalischen körper des Männchens
            if (characterBody == null) {
                b2BodyDef characterDef = new b2BodyDef ();
                characterDef.type = b2BodyType.b2_dynamicBody;
                characterDef.position = new b2Vec2 (CharacterPosition.X / PhysicsHandler.pixelPerMeter, CharacterPosition.Y / PhysicsHandler.pixelPerMeter);
                characterBody = bodyWorld.CreateBody (characterDef);

                b2PolygonShape characterShape = new b2PolygonShape ();
                characterShape.SetAsBox ((float)CharacterSize.Width / PhysicsHandler.pixelPerMeter / 2, (float)CharacterSize.Height / PhysicsHandler.pixelPerMeter / 2);

                b2FixtureDef characterFixture = new b2FixtureDef ();
                characterFixture.shape = characterShape;
                characterFixture.density = 0.0f; //Dichte
                characterFixture.friction = 0f;
                characterFixture.restitution = 0f; //Rückprall
                characterBody.CreateFixture (characterFixture);

                b2PolygonShape characterGroundSensorShape = new b2PolygonShape ();
                b2Vec2 GroundSensorPosition = new b2Vec2 (0f, -0.29f * CharacterSprite.ScaleY);
                characterGroundSensorShape.SetAsBox (((float)CharacterSize.Width - 1f) / PhysicsHandler.pixelPerMeter / 2, 5f / PhysicsHandler.pixelPerMeter, GroundSensorPosition, 0f);

                //untergrundsensor
                b2FixtureDef groundSensor = new b2FixtureDef ();
                groundSensor.isSensor = true;
                groundSensor.userData = WorldFixtureData.playergroundsensor;
                groundSensor.shape = characterGroundSensorShape;
                groundSensor.density = 0.0f; //Dichte
                groundSensor.friction = 0f;
                groundSensor.restitution = 0f; //Rückprall
                characterBody.CreateFixture (groundSensor);

                b2PolygonShape characterLeftSensorShape = new b2PolygonShape ();
                b2Vec2 LeftSensorPosition = new b2Vec2 (-0.15f * CharacterSprite.ScaleX, -0.5f);
                characterLeftSensorShape.SetAsBox ((float)5f / PhysicsHandler.pixelPerMeter, CharacterSize.Height / PhysicsHandler.pixelPerMeter / 4, LeftSensorPosition, 0f);

                //leftsensor
                b2FixtureDef leftSensor = new b2FixtureDef ();
                leftSensor.isSensor = true;
                leftSensor.userData = WorldFixtureData.playerleftsensor;
                leftSensor.shape = characterLeftSensorShape;
                leftSensor.density = 0.0f; //Dichte
                leftSensor.friction = 0f;
                leftSensor.restitution = 0f; //Rückprall
                characterBody.CreateFixture (leftSensor);

                b2PolygonShape characterRightSensorShape = new b2PolygonShape ();
                b2Vec2 RightSensorPosition = new b2Vec2 (0.15f * CharacterSprite.ScaleX, -0.5f);
                characterRightSensorShape.SetAsBox ((float)5f / PhysicsHandler.pixelPerMeter, CharacterSize.Height / PhysicsHandler.pixelPerMeter / 4, RightSensorPosition, 0f);

                //rightsensor
                b2FixtureDef rightSensor = new b2FixtureDef ();
                rightSensor.isSensor = true;
                rightSensor.userData = WorldFixtureData.playerrightsensor;
                rightSensor.shape = characterRightSensorShape;
                rightSensor.density = 0.0f; //Dichte
                rightSensor.friction = 0f;
                rightSensor.restitution = 0f; //Rückprall
                characterBody.CreateFixture (rightSensor);
            }

            return characterBody;
        }
            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

            }
Example #19
0
        public b2Body N2b2Body(b2World world, JObject bodyValue)
        {
            b2BodyDef bodyDef = new b2BodyDef();

            switch ((int)bodyValue.GetValue("type"))
            {
                case 0:
                    bodyDef.type = b2BodyType.b2_staticBody;
                    break;
                case 1:
                    bodyDef.type = b2BodyType.b2_kinematicBody;
                    break;
                case 2:
                    bodyDef.type = b2BodyType.b2_dynamicBody;
                    break;
            }

            bodyDef.position = jsonToVec("position", bodyValue);
            bodyDef.angle = jsonToFloat("angle", bodyValue);
            bodyDef.linearVelocity = jsonToVec("linearVelocity", bodyValue);
            bodyDef.angularVelocity = jsonToFloat("angularVelocity", bodyValue);
            bodyDef.linearDamping = jsonToFloat("linearDamping", bodyValue, -1, 0);
            bodyDef.angularDamping = jsonToFloat("angularDamping", bodyValue, -1, 0);
            bodyDef.gravityScale = jsonToFloat("gravityScale", bodyValue, -1, 1);

            bodyDef.allowSleep = bodyValue["allowSleep"] == null ? false : (bool)bodyValue["allowSleep"];
            bodyDef.awake = bodyValue["awake"] == null ? false : (bool)bodyValue["awake"];
            bodyDef.fixedRotation = bodyValue["fixedRotation"] == null ? false : (bool)bodyValue["fixedRotation"];
            bodyDef.bullet = bodyValue["bullet"] == null ? false : (bool)bodyValue["bullet"];

            //bodyDef.active = bodyValue["active"] == null ? false : (bool)bodyValue["active"];

            bodyDef.active = true;

            b2Body body = world.CreateBody(bodyDef);
            String bodyName = bodyValue["name"] == null ? "" : (string)bodyValue["active"];

            if ("" != bodyName)
                SetBodyName(body, bodyName);

            int i = 0;

            JArray fixtureValues = (JArray)bodyValue["fixture"];
            if (null != fixtureValues)
            {
                int numFixtureValues = fixtureValues.Count;
                for (i = 0; i < numFixtureValues; i++)
                {
                    JObject fixtureValue = (JObject)fixtureValues[i];
                    b2Fixture fixture = j2b2Fixture(body, fixtureValue);
                    readCustomPropertiesFromJson(fixture, fixtureValue);
                }
            }

            // may be necessary if user has overridden mass characteristics
            b2MassData massData = new b2MassData();
            massData.mass = jsonToFloat("massData-mass", bodyValue);
            massData.center = jsonToVec("massData-center", bodyValue);
            massData.I = jsonToFloat("massData-I", bodyValue);
            body.SetMassData(massData);

            return body;
        }
		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);
		}
Example #21
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,
            });
        }