public Enemy(World world, GameContent gameContent, int index, Vector2 position)
        {
            this.gameContent = gameContent;

            walk = new Animation(gameContent.enemy[index], 2, 0.15f, true, new Vector2(0.5f));
            animationPlayer.PlayAnimation(walk);

            if (index == 0) linearImpulse = 1f / 2;
            else linearImpulse = 0.75f / 2;

            BodyDef bd = new BodyDef();
            bd.position = position / gameContent.b2Scale;
            bd.type = BodyType.Dynamic;
            bd.linearDamping = 10;
            body = world.CreateBody(bd);

            CircleShape cs = new CircleShape();
            cs._radius = (float)(walk.FrameWidth - 1) / gameContent.b2Scale / 2;
            FixtureDef fd = new FixtureDef();
            fd.shape = cs;
            fd.filter.groupIndex = -1;

            body.CreateFixture(fd);
            body.SetUserData(this);
        }
Exemplo n.º 2
0
        public Body CreateBall(World world, float ScaleFactor)
        {
            var bodyDef = new BodyDef();

            bodyDef.type = BodyType.Dynamic;

            var ballShape = new CircleShape();

            ballShape._radius = (texture.Width / 2f) * ScaleFactor;

            var ballFixture = new FixtureDef();

            ballFixture.friction = 0.0f; // no friction

            ballFixture.restitution = 1.0f; // give the ball a perfect bounce

            ballFixture.density = 1.0f;

            ballFixture.shape = ballShape;

            var ballBody = world.CreateBody(bodyDef);

            ballBody.CreateFixture(ballFixture);

            // ballBody.Position = new Vector2(((float)r.NextDouble() * 4.5f + .3f), (float)r.NextDouble() * 4.5f + .3f);

            //ballBodies.Add(ballBody);

            return ballBody;
        }
        public Soldier(Shape shape, Vector2 position, GameContent gameContent, World world)
        {
            this.gameContent = gameContent;
            this.world = world;

            idle = new Animation(gameContent.idle[(int)shape], 20f, false);
            walk = new Animation(gameContent.walk[(int)shape], 0.15f, true);
            animationPlayer.PlayAnimation(idle);

            MaxHealth = 10; health = gameContent.random.Next(2, 10);
            MaxReloadTime = gameContent.random.Next(50); reloadTime = 0;

            CircleShape cShape = new CircleShape();
            cShape._radius = (Size + 2) / 2 / gameContent.b2Scale;

            BodyDef bd = new BodyDef();
            bd.fixedRotation = true;
            bd.type = BodyType.Dynamic;
            bd.position = position / gameContent.b2Scale;
            body = world.CreateBody(bd);
            //body.SetLinearDamping(10);

            FixtureDef fd = new FixtureDef();
            fd.shape = cShape;
            fd.restitution = 0.5f;
            fd.friction = .1f;
            fd.density = .1f;

            body.CreateFixture(fd);
            body.SetUserData(this);
        }
        public PhysicsCircle(Texture2D sprite_texture, World physicsWorld, float radius,
            float positionX, float positionY, float rotation, float density)
            : base(sprite_texture)
        {
            this.scaleToFitTheseDimensions(radius*2.0f, radius*2.0f);
            this.position.X = positionX;
            this.position.Y = positionY;
            this.rotation = rotation;

            BodyDef dynamicBodyDef = new BodyDef();
            dynamicBodyDef.type = BodyType.Dynamic;
            dynamicBodyDef.position = new Vector2(positionX / ScreenPixelsPerMeter, positionY / ScreenPixelsPerMeter);
            dynamicBodyDef.linearDamping = 0.0f;
            Body dynamicBody = physicsWorld.CreateBody(dynamicBodyDef);

            CircleShape dynamicCircleShape = new CircleShape();
            dynamicCircleShape._radius = radius/DynamicPhysicsGameObject.ScreenPixelsPerMeter;
            //dynamicBoxShape.
            //dynamicBoxShape.SetAsBox(box_width / 2.0f, box_height / 2.0f);   //experiment with / 2.0f
            FixtureDef dynamicCircleFixtureDef = new FixtureDef();
            dynamicCircleFixtureDef.shape = dynamicCircleShape;
            dynamicCircleFixtureDef.density = density;
            dynamicCircleFixtureDef.friction = 0.3f;

            dynamicBody.CreateFixture(dynamicCircleFixtureDef);

            this.physicsBody = dynamicBody;
        }
Exemplo n.º 5
0
        public Car(Vector2 position, GameContent gameContent, World world)
        {
            this.world = world;
            this.gameContent = gameContent;

            BodyDef bd = new BodyDef();
            bd.position = position / gameContent.Scale;
            bd.type = BodyType.Dynamic;
            bd.bullet = true;

            body = world.CreateBody(bd);
            body.SetLinearDamping(1f); body.SetAngularDamping(0.1f);

            float width = gameContent.playerCar.Width, height = gameContent.playerCar.Height;

            FixtureDef fd = new FixtureDef();
            fd.density = 0.1f;
            //fd.restitution = .1f;

            CircleShape cs = new CircleShape();
            cs._p = new Vector2(0, -(height - width / 2)) / gameContent.Scale;
            cs._radius = width / 2 / gameContent.Scale;
            fd.shape = cs; body.CreateFixture(fd);

            PolygonShape ps = new PolygonShape();
            ps.SetAsBox(width / 2 / gameContent.Scale, (height - width / 2) / 2 / gameContent.Scale,
                new Vector2(0, -(height - width / 2) / 2) / gameContent.Scale, 0);
            fd.shape = ps; body.CreateFixture(fd);

            CreateWheels();
        }
        public Player(GameContent gameContent, World world, Vector2 position)
        {
            this.gameContent = gameContent;
            this.world = world;

            idle = new Animation(gameContent.playerIdle, 2, 2f, true, new Vector2(0.5f));
            walk = new Animation(gameContent.playerWalk, 2, 0.2f, true, new Vector2(0.5f));
            die = new Animation(gameContent.playerDie, 2, 0.2f, false, new Vector2(0.5f));

            animationPlayer.PlayAnimation(idle);

            BodyDef bd = new BodyDef();
            bd.position = position / gameContent.b2Scale;
            bd.type = BodyType.Dynamic;
            bd.linearDamping = 10;
            body = world.CreateBody(bd);

            CircleShape cs = new CircleShape();
            cs._radius = (float)(idle.FrameWidth - 1) / gameContent.b2Scale / 2;
            FixtureDef fd = new FixtureDef();
            fd.shape = cs;
            fd.filter.groupIndex = -1;

            body.CreateFixture(fd);
        }
Exemplo n.º 7
0
        public override void Initialize(ConfigSection section)
        {
            base.Initialize(section);

            textureName = section["texture"];
            circlePos = section["position"].AsVector2();
            Radius = section["radius"];
            MaxTorque = section["torque"];

            var bodyDef = new BodyDef();
            bodyDef.type = BodyType.Dynamic;

            bodyDef.position = Game.level.ConvertToBox2D(circlePos);
            bodyDef.inertiaScale = section["inertiaScale"];
            bodyDef.linearDamping = section["linearDamping"];
            bodyDef.angularDamping = section["angularDamping"];

            bodyDef.userData = this;

            Body = Game.level.World.CreateBody(bodyDef);

            var shape = new CircleShape();
            shape._radius = Game.level.ConvertToBox2D(Radius);

            var fixture = new FixtureDef();
            fixture.restitution = section["restitution"];
            fixture.density = section["density"];
            fixture.shape = shape;
            fixture.friction = section["friction"];
            Body.CreateFixture(fixture);
        }
Exemplo n.º 8
0
        public override bool init()
        {
            if (!base.init())
                return false;
            if (!base.init())
            {
                return false;
            }

            CCSize winSize = CCDirector.sharedDirector().getWinSize();
            title = CCLabelTTF.labelWithString("FootBall", "Arial", 24);
            title.position = new CCPoint(winSize.width / 2, winSize.height - 50);
            this.addChild(title, 1);
            ball = CCSprite.spriteWithFile(@"images/ball");
            ball.position = new CCPoint(100, 300);
            this.addChild(ball);
            Vector2 gravity = new Vector2(0.0f, -30.0f);
            bool doSleep = true;
            world = new World(gravity, doSleep);
            /////////////////////////
            BodyDef groundBodyDef = new BodyDef();
            groundBodyDef.position = new Vector2(0, 0);
            Body groundBody = world.CreateBody(groundBodyDef);
            PolygonShape groundBox = new PolygonShape();
            FixtureDef boxShapeDef = new FixtureDef();
            boxShapeDef.shape = groundBox;

            groundBox.SetAsEdge(new Vector2(0, 0), new Vector2((float)(winSize.width / PTM_RATIO), 0));
            groundBody.CreateFixture(boxShapeDef);
            groundBox.SetAsEdge(new Vector2(0, 0), new Vector2(0, (float)(winSize.height / PTM_RATIO)));
            groundBody.CreateFixture(boxShapeDef);
            groundBox.SetAsEdge(new Vector2(0, (float)(winSize.height / PTM_RATIO)),
                new Vector2((float)(winSize.width / PTM_RATIO), (float)(winSize.height / PTM_RATIO)));
            groundBody.CreateFixture(boxShapeDef);
            groundBox.SetAsEdge(new Vector2((float)(winSize.width / PTM_RATIO), (float)(winSize.height / PTM_RATIO)),
                new Vector2((float)(winSize.width / PTM_RATIO), 0));
            groundBody.CreateFixture(boxShapeDef);

            BodyDef ballBodyDef = new BodyDef();
            ballBodyDef.type = BodyType.Dynamic;
            ballBodyDef.position = new Vector2(
                (float)(100 / PTM_RATIO),
                (float)(300 / PTM_RATIO));
            ballBodyDef.userData = ball;
            body = world.CreateBody(ballBodyDef);

            CircleShape circle = new CircleShape();
            circle._radius = (float)(26.0 / PTM_RATIO);

            FixtureDef ballShapeDef = new FixtureDef();
            ballShapeDef.shape = circle;
            ballShapeDef.density = 1.0f;
            ballShapeDef.friction = 0.0f;
            ballShapeDef.restitution = 1.0f;
            body.CreateFixture(ballShapeDef);

            this.schedule(tick);
            return true;
        }
Exemplo n.º 9
0
 public Terrain(World world)
 {
     mWorld = world;
     mBodyDef = new BodyDef();
     mBody = world.CreateBody(mBodyDef);
     Generate();
     GenerateDrawVertexs();
 }
        public Atom(Symbol symbol, Vector2 position, GameContent gameContent, World world)
        {
            this.gameContent = gameContent;
            this.world = world;

            if (symbol == Symbol.Ra) eye = EyeState.Angry;

            this.symbol = symbol;
            this.symbolStr = symbol.ToString();
            symbolCenter = gameContent.symbolFont.MeasureString(this.symbolStr);
            symbolCenter.X *= 0.5f;
            symbolCenter.Y *= 0.92f;

            bondsLeft = (int)symbol;

            BodyDef bd = new BodyDef();
            bd.type = BodyType.Dynamic;
            bd.position = this.position = position / gameContent.b2Scale;
            bd.bullet = true;
            body = world.CreateBody(bd);
            body.SetUserData(this);

            CircleShape cs = new CircleShape();
            cs._radius = gameContent.atomRadius / gameContent.b2Scale;

            FixtureDef fd = new FixtureDef();
            fd.shape = cs;
            fd.restitution = 0.2f;
            fd.friction = 0.5f;

            fixture = body.CreateFixture(fd);

            electroShockAnimation = new Animation(gameContent.electroShock, 3, 0.1f, true, new Vector2(0.5f, 0.5f));

            radiationSmoke = new RadiationSmoke(gameContent, this);

            // Collide only with Ground but not with itself and bonded Filter
            mouseFilter = new Filter();
            mouseFilter.categoryBits = 0x0002; mouseFilter.maskBits = 0x0001; mouseFilter.groupIndex = -2;

            // Collide with every thing
            atomFilter = new Filter();
            atomFilter.categoryBits = 0x0001; atomFilter.maskBits = 0x0001; atomFilter.groupIndex = 1;

            fixture.SetFilterData(ref atomFilter);

            SetMode(false, false);
        }
        public LevelComponent(GameContent gameContent, World world)
        {
            this.gameContent = gameContent;
            this.world = world;

            levelData = gameContent.content.Load<LevelData>("Levels/level" + gameContent.levelIndex);

            MaxAtoms = levelData.MaxAtoms;

            int totalProbability = 0;
            for (int i = 0; i < levelData.AtomProbability.Length; i++) totalProbability += levelData.AtomProbability[i];

            if (totalProbability != 100) throw new Exception("must be 100");

            entryPoint = levelData.Entry;

            bonusType = levelData.BonusType;

            BodyDef bd = new BodyDef();
            Body ground = world.CreateBody(bd);

            PolygonShape ps = new PolygonShape();

            List<Vector2> v = levelData.ContinuousBoundry;
            for (int i = 0; i < v.Count - 1; i++)
            {
                if (v[i + 1].X == -1 && v[i + 1].Y == -1) { i++; continue; }

                ps.SetAsEdge(v[i] / gameContent.scale, v[i + 1] / gameContent.scale);
                ground.CreateFixture(ps, 0);
            }

            for (int i = 0; i < levelData.EquipmentDetails.Count; i++)
            {
                Equipment eq = new Equipment(levelData.EquipmentDetails[i].EquipmentName, gameContent, world);
                eq.body.Position = levelData.EquipmentDetails[i].Position / gameContent.scale;
                eq.body.Rotation = levelData.EquipmentDetails[i].RotationInDeg / 180 * (float)MathHelper.Pi;
                eq.isClamped = levelData.EquipmentDetails[i].IsClamped;
                eq.body.SetType(BodyType.Static);
                equipments.Add(eq);

                if (eq.equipName == EquipmentName.thermometer) thermometer = eq;

                if (eq.equipName == EquipmentName.pHscale) pHscale = eq;
            }
        }
Exemplo n.º 12
0
        public void addRect(float x, float y, float width, int height, object type)
        {
            PolygonShape ps = new PolygonShape();
            ps.SetAsBox(width / PTM / 2, height / PTM / 2);

            FixtureDef fd = new FixtureDef();
            fd.shape = ps;
            fd.restitution = 0.0f;
            fd.friction = 0.8f;
            fd.density = 1.0f;

            BodyDef bd = new BodyDef();
            bd.type = BodyType.Static;
            bd.position = new Vector2(x / PTM, y / PTM);
            bd.userData = type;

            Body body = world.CreateBody(bd);
            body.CreateFixture(fd);
        }
Exemplo n.º 13
0
        public void addCharacterSprite(Sprite sprite)
        {
            CircleShape cs = new CircleShape();
            cs._radius = sprite.Texture2D.Width / PTM;

            FixtureDef fd = new FixtureDef();
            fd.shape = cs;
            fd.restitution = 0.5f;
            fd.friction = 0.5f;
            fd.density = 1.5f;

            BodyDef bd = new BodyDef();
            bd.type = BodyType.Dynamic;
            bd.position = new Vector2(sprite.X / PTM, sprite.Y / PTM);
            bd.userData = sprite;

            Body body = world.CreateBody(bd);
            body.CreateFixture(fd);
        }
Exemplo n.º 14
0
        public Box(World world, Vector2 position, Vector2 size, string texture, bool isStatic, Player player, float health = 100)
        {
            ObjectType = EObjectType.Box;
            mHealth = health;
            mStartHealth = health;
            mIsDestroyed = false;
            mSize = size;
            mWorld = world;
            mTexture = texture;
            mPlayer = player;
            DestroyTime = null;
            PolygonShape polygonShape = new PolygonShape();
            polygonShape.SetAsBox(size.X / 2f, size.Y / 2f);

            BodyDef bodyDef = new BodyDef();
            bodyDef.position = position;
            bodyDef.bullet = true;
            if (isStatic)
            {
                bodyDef.type = BodyType.Static;
            }
            else
            {
                bodyDef.type = BodyType.Dynamic;
            }
            mBody = world.CreateBody(bodyDef);

            FixtureDef fixtureDef = new FixtureDef();
            fixtureDef.shape = polygonShape;//Форма
            fixtureDef.density = 0.1f;//Плотность
            fixtureDef.friction = 0.3f;//Сила трения
            fixtureDef.restitution = 0f;//Отскок

            Filter filter = new Filter();
            filter.maskBits = (ushort)(EntityCategory.Player1 | EntityCategory.Player2);
            filter.categoryBits = (ushort)player.PlayerType;

            var fixture = mBody.CreateFixture(fixtureDef);
            fixture.SetFilterData(ref filter);
            MassData data = new MassData();
            data.mass = 0.01f;
            mBody.SetUserData(this);
        }
Exemplo n.º 15
0
        public Body CreateWall(World world, float ScaleFactor)
        {
            var grounDef = new BodyDef();
            grounDef.type = BodyType.Static;

            var groundFix = new FixtureDef();
            groundFix.restitution = 1.0f;
            groundFix.friction = 0.0f;
            groundFix.density = 0.0f;

            var groundShape = new PolygonShape();
            //groundShape.SetAsEdge(new Vector2(0, 8), new Vector2(4.8f, 8.0f));
            groundShape.SetAsBox(texture.Width * ScaleFactor / 2f, texture.Height * ScaleFactor / 2f);

            var groundBody = world.CreateBody(grounDef);
            groundBody.Position = new Vector2(2.4f, 4);
            groundFix.shape = groundShape;
            groundBody.CreateFixture(groundFix);

            return groundBody;
        }
        public Branch(Path2D path, GameContent gameContent, World world, Branch nearestBranch)
        {
            this.gameContent = gameContent;
            dot = gameContent.dot;
            circle = gameContent.jointCircle;
            square = gameContent.jointSquare;
            cursor = gameContent.cursor;

            BodyDef bd = new BodyDef();
            bd.position = path.Keys[0];
            bd.type = BodyType.Dynamic;
            body = world.CreateBody(bd);

            fixtureCount = path.Keys.Count;
            for (int i = 0; i < path.Keys.Count; i++)
                CreateFixture(path.Keys[i] - path.Keys[0]);

            if (nearestBranch != null)
            {
                RevoluteJointDef revJd = new RevoluteJointDef();
                revJd.bodyA = body;
                revJd.bodyB = nearestBranch.body;

                revJd.localAnchorA = Vector2.Zero;

                AABB aabb; nearestBranch.nearestFixture.GetAABB(out aabb);
                Vector2 p = aabb.GetCenter();
                revJd.localAnchorB = nearestBranch.nearestFixture.GetBody().GetLocalPoint(p);

                revJd.enableMotor = true;
                revJd.referenceAngle = nearestBranch.nearestFixture.GetBody().Rotation;

                revoJoint = (RevoluteJoint)world.CreateJoint(revJd);
                revoJoint.SetUserData((Branch)nearestBranch);

                nearestBranch.nearestFixture.SetUserData((Branch)this);
            }

            newGrow = true;
        }
        public Equipment(EquipmentName equipName, GameContent gameContent, World world)
        {
            this.gameContent = gameContent;
            this.world = world;

            this.equipName = equipName;
            BodyDef bd = new BodyDef();
            bd.type = BodyType.Dynamic;
            body = world.CreateBody(bd);

            equipmentData = gameContent.content.Load<EquipmentData>("Graphics/" + equipName.ToString());

            topLeftVertex = equipmentData.TopLeftVertex;
            origin = equipmentData.Origin;
            rotationButtonPos = equipmentData.RotationButtonPosition;

            rightClampPositionX = equipmentData.ClampData.RightClampPositionX;
            clampRotation = equipmentData.ClampData.RotationInDeg / 180f * (float)Math.PI;
            clampEnabled = equipmentData.ClampData.ClampEnabled;

            SetFixtures();

            // Collide only with Ground but not with itself and bonded Filter
            mouseFilter = new Filter();
            mouseFilter.categoryBits = 0x0002; mouseFilter.maskBits = 0x0001; mouseFilter.groupIndex = -2;

            // Collide with every thing
            groundFilter = new Filter();
            groundFilter.categoryBits = 0x0001; groundFilter.maskBits = 65535; groundFilter.groupIndex = 0;

            equipFilter = new Filter();
            equipFilter.categoryBits = 0x0002; equipFilter.maskBits = 0x0001; equipFilter.groupIndex = 2;

            //SetMode(false, false);

            body.SetUserData((EquipmentName)equipName);
        }
        public PhysicsBox(Texture2D sprite_texture, World physicsWorld, float box_width, float box_height, 
            float positionX, float positionY, float rot, float density)
            : base(sprite_texture)
        {
            this.scaleToFitTheseDimensions(box_width, box_height);
            this.position.X = positionX;
            this.position.Y = positionY;

            BodyDef dynamicBodyDef = new BodyDef();
            dynamicBodyDef.type = BodyType.Dynamic;
            dynamicBodyDef.position = new Vector2(positionX/DynamicPhysicsGameObject.ScreenPixelsPerMeter, positionY/DynamicPhysicsGameObject.ScreenPixelsPerMeter);
            dynamicBodyDef.angle = rot;
            Body dynamicBody = physicsWorld.CreateBody(dynamicBodyDef);

            PolygonShape dynamicBoxShape = new PolygonShape();
            dynamicBoxShape.SetAsBox((box_width/ScreenPixelsPerMeter) / 2.0f, (box_height/ScreenPixelsPerMeter) / 2.0f);   //experiment with / 2.0f
            FixtureDef dynamicBoxFixtureDef = new FixtureDef();
            dynamicBoxFixtureDef.shape = dynamicBoxShape;
            dynamicBoxFixtureDef.density = density;
            dynamicBoxFixtureDef.friction = 0.3f;
            dynamicBody.CreateFixture(dynamicBoxFixtureDef);

            this.physicsBody = dynamicBody;
        }
Exemplo n.º 19
0
        public virtual Body AddBodyInstanceToRuntime()
        {
            // box2D body
            if (this.polygons.Count > 0)
            {
                BodyDef bodyDef = new BodyDef();
                Vector2 pos = GetGlobalOffset(Vector2.Zero);
                bodyDef.position = new Vector2(pos.X / V2DScreen.WorldScale, pos.Y / V2DScreen.WorldScale);
                bodyDef.angle = GetGlobalRotation(0);
                bodyDef.fixedRotation = this.fixedRotation;
                bodyDef.angularDamping = this.angularDamping;
                bodyDef.linearDamping = this.linearDamping;

                IsStatic = isStatic;
                // todo: add kinematic
                if (isStatic)
                {
                    bodyDef.type = BodyType.Static;
                }
                else
                {
                    bodyDef.type = BodyType.Dynamic;
                }

                //// todo: this needs to allow for nested levels
                //if (!fixedRotation)
                //{
                //    for (int i = 0; i < transforms.Length; i++)
                //    {
                //        transforms[i].Position = transforms[i].Position - pos + State.Position;
                //        transforms[i].Rotation = transforms[i].Rotation - bodyDef.Angle + State.Rotation;
                //        //this.transforms[i].Scale /= bodyDef.Scale;
                //    }
                //}

                if (attributeProperties != null)
                {
                    attributeProperties.ApplyAttribtues(bodyDef);
                }

                body = v2dScreen.CreateBody(bodyDef);
                body.SetUserData(this);

                for (int i = 0; i < this.polygons.Count; i++)
                {
                    AddPoly(body, this.polygons[i]);
                }

                if (attributeProperties != null)
                {
                    if (attributeProperties.mass != 0f)
                    {
                        MassData md;
                        body.GetMassData(out md);
                        md.mass = attributeProperties.mass;
                        body.SetMassData(ref md);
                    }

                    if (attributeProperties.centerOfMassX != 0 || attributeProperties.centerOfMassY != 0)
                    {
                        MassData md;
                        body.GetMassData(out md);
                        md.center = new Vector2(attributeProperties.centerOfMassX, attributeProperties.centerOfMassY);
                        body.SetMassData(ref md);
                    }
                }
            }
            return body;
        }
        public void SetMode(bool editMode, bool isMouse)
        {
            if (!clampEnabled) isClamped = false;

            this.editMode = editMode;
            float reqMass = 10;

            if (isSelected) reqMass = .2f;
            else
            {
                body.SetActive(true); body.SetLinearDamping(0); body.SetAngularDamping(0);
            }

            for (Fixture f = body.GetFixtureList(); f != null; f = f.GetNext())
            {
                object area = f.GetUserData();
                if (area is float) f.SetDensity(reqMass / (float)area / fixtureCount);

                if (isSelected) f.SetFilterData(ref mouseFilter);
                else if (editMode) f.SetFilterData(ref equipFilter);
                else f.SetFilterData(ref groundFilter);
            }

            body.ResetMassData();

            if (!editMode || (isSelected && !isMouse) || isClamped)
            {
                if (pin == null) // Pin
                {
                    BodyDef bd = new BodyDef(); Body b = world.CreateBody(bd);

                    RevoluteJointDef jd = new RevoluteJointDef();
                    jd.bodyA = b; jd.bodyB = body; jd.localAnchorA = body.Position; jd.localAnchorB = Vector2.Zero;
                    pin = world.CreateJoint(jd);

                    body.SetAngularVelocity(0); body.SetFixedRotation(true);
                }
            }
            else if (pin != null)
            {
                body.SetFixedRotation(false); world.DestroyJoint(pin); pin = null;
            }
        }
Exemplo n.º 21
0
    public EdgeTest()
    {
        {
            BodyDef bd = new BodyDef();
            Body ground = _world.CreateBody(bd);

            Vector2 v1 = new Vector2(-10.0f, 0.0f);
            Vector2 v2 = new Vector2(-7.0f, -1.0f);
            Vector2 v3 = new Vector2(-4.0f, 0.0f);
            Vector2 v4 = new Vector2(0.0f, 0.0f);
            Vector2 v5 = new Vector2(4.0f, 0.0f);
            Vector2 v6 = new Vector2(7.0f, 1.0f);
            Vector2 v7 = new Vector2(10.0f, 0.0f);

            EdgeShape shape = new EdgeShape();

            shape.Set(v1, v2);
            //shape._index1 = 0;
            //shape._index2 = 1;
            shape._hasVertex3 = true;
            shape._vertex3 = v3;
            ground.CreateFixture(shape, 0.0f);

            shape.Set(v2, v3);
            //shape._index1 = 1;
            //shape._index2 = 2;
            shape._hasVertex0 = true;
            shape._hasVertex3 = true;
            shape._vertex0 = v1;
            shape._vertex3 = v4;
            ground.CreateFixture(shape, 0.0f);

            shape.Set(v3, v4);
            //shape._index1 = 2;
            //shape._index2 = 3;
            shape._hasVertex0 = true;
            shape._hasVertex3 = true;
            shape._vertex0 = v2;
            shape._vertex3 = v5;
            ground.CreateFixture(shape, 0.0f);

            shape.Set(v4, v5);
            //shape._index1 = 3;
            //shape._index2 = 4;
            shape._hasVertex0 = true;
            shape._hasVertex3 = true;
            shape._vertex0 = v3;
            shape._vertex3 = v6;
            ground.CreateFixture(shape, 0.0f);

            shape.Set(v5, v6);
            //shape._index1 = 4;
            //shape._index2 = 5;
            shape._hasVertex0 = true;
            shape._hasVertex3 = true;
            shape._vertex0 = v4;
            shape._vertex3 = v7;
            ground.CreateFixture(shape, 0.0f);

            shape.Set(v6, v7);
            //shape._index1 = 5;
            //shape._index2 = 6;
            shape._hasVertex0 = true;
            shape._vertex0 = v5;
            ground.CreateFixture(shape, 0.0f);
        }

        {
            BodyDef bd = new BodyDef();
            bd.type = BodyType.Dynamic;
            bd.position = new Vector2(-0.5f, 0.5f);
            bd.allowSleep = false;
            Body body = _world.CreateBody(bd);

            CircleShape shape = new CircleShape();
            shape._radius = 0.5f;

            body.CreateFixture(shape, 1.0f);
        }

        {
            BodyDef bd = new BodyDef();
            bd.type = BodyType.Dynamic;
            bd.position = new Vector2(0.5f, 0.5f);
            bd.allowSleep = false;
            Body body = _world.CreateBody(bd);

            PolygonShape shape = new PolygonShape();
            shape.SetAsBox(0.5f, 0.5f);

            body.CreateFixture(shape, 1.0f);
        }
    }
Exemplo n.º 22
0
        /// <summary>
        /// Call this to initialize a Behaviour with data supplied in a file.
        /// </summary>
        /// <param name="fileName">The file to load from.</param>
        public override void LoadContent(String fileName)
        {
            base.LoadContent(fileName);

            // Load the definiton for this object.
            SimulatedPhysicsDefinition def = GameObjectManager.pInstance.pContentManager.Load<SimulatedPhysicsDefinition>(fileName);

            // Create the body representing this object in the physical world.
            BodyDef bd = new BodyDef();
            bd.type = BodyType.Dynamic;
            bd.position = PhysicsManager.pInstance.ScreenToPhysicalWorld(new Vector2(640.0f, 340.0f));
            bd.fixedRotation = true;
            bd.linearDamping = 1.0f;
            mBody = PhysicsManager.pInstance.pWorld.CreateBody(bd);

            /*
            // A bunch of code to create a capsule.  Not using it because it has all the same problems as
            // a box when it comes to catching edges and such.
            var shape = new PolygonShape();
            Vector2[] v = new Vector2[8];

            Double increment = System.Math.PI * 2.0 / (v.Length - 2);
            Double theta = 0.0;

            Vector2 center = PhysicsManager.pInstance.ScreenToPhysicalWorld(new Vector2(0.0f, 8.0f));
            Single radius = PhysicsManager.pInstance.ScreenToPhysicalWorld(8.0f);
            for (Int32 i = 0; i < v.Length; i++)
            {
                v[i] = center + radius * new Vector2((float)System.Math.Cos(theta), (float)System.Math.Sin(theta));

                if (i == (v.Length / 2) - 1)
                {
                    center = PhysicsManager.pInstance.ScreenToPhysicalWorld(new Vector2(0.0f, -8.0f));
                    i++;
                    v[i] = center + radius * new Vector2((float)System.Math.Cos(theta), (float)System.Math.Sin(theta));
                }
                theta += increment;
            }

            //v = v.Reverse().ToArray();

            shape.Set(v, v.Length);

            var fd = new FixtureDef();
            fd.shape = shape;
            fd.restitution = 0.0f;
            fd.friction = 0.5f;
            fd.density = 1.0f;
            mBody.CreateFixture(fd);
            */

            var shape = new PolygonShape();
            shape.SetAsBox(PhysicsManager.pInstance.ScreenToPhysicalWorld(8.0f), PhysicsManager.pInstance.ScreenToPhysicalWorld(8.0f));

            var fd = new FixtureDef();
            fd.shape = shape;
            fd.restitution = 0.0f;
            fd.friction = 0.5f;
            fd.density = 1.0f;
            //mBody.CreateFixture(fd);

            var circle = new CircleShape();
            circle._radius = PhysicsManager.pInstance.ScreenToPhysicalWorld(8);
            circle._p = PhysicsManager.pInstance.ScreenToPhysicalWorld(new Vector2(0.0f, 8.0f));

            fd = new FixtureDef();
            fd.shape = circle;
            fd.restitution = 0.0f;
            fd.friction = 0.5f;
            fd.density = 1.5f;
            mBody.CreateFixture(fd);

            circle = new CircleShape();
            circle._radius = PhysicsManager.pInstance.ScreenToPhysicalWorld(8);
            circle._p = PhysicsManager.pInstance.ScreenToPhysicalWorld(new Vector2(0.0f, -8.0f));

            fd = new FixtureDef();
            fd.shape = circle;
            fd.restitution = 0.0f;
            fd.friction = 0.5f;
            fd.density = 1.5f;
            mBody.CreateFixture(fd);
        }
Exemplo n.º 23
0
    public CharacterCollision()
    {
        // Ground body
        {
            BodyDef bd = new BodyDef();
            Body ground = _world.CreateBody(bd);

            PolygonShape shape = new PolygonShape();
            shape.SetAsEdge(new Vector2(-20.0f, 0.0f), new Vector2(20.0f, 0.0f));
            ground.CreateFixture(shape, 0.0f);
        }

        // Collinear edges
        {
            BodyDef bd = new BodyDef();
            Body ground = _world.CreateBody(bd);

            PolygonShape shape = new PolygonShape();
            shape.SetAsEdge(new Vector2(-8.0f, 1.0f), new Vector2(-6.0f, 1.0f));
            ground.CreateFixture(shape, 0.0f);
            shape.SetAsEdge(new Vector2(-6.0f, 1.0f), new Vector2(-4.0f, 1.0f));
            ground.CreateFixture(shape, 0.0f);
            shape.SetAsEdge(new Vector2(-4.0f, 1.0f), new Vector2(-2.0f, 1.0f));
            ground.CreateFixture(shape, 0.0f);
        }

        // Square tiles
        {
            BodyDef bd = new BodyDef();
            Body ground = _world.CreateBody(bd);

            PolygonShape shape = new PolygonShape();
            shape.SetAsBox(1.0f, 1.0f, new Vector2(4.0f, 3.0f), 0.0f);
            ground.CreateFixture(shape, 0.0f);
            shape.SetAsBox(1.0f, 1.0f, new Vector2(6.0f, 3.0f), 0.0f);
            ground.CreateFixture(shape, 0.0f);
            shape.SetAsBox(1.0f, 1.0f, new Vector2(8.0f, 3.0f), 0.0f);
            ground.CreateFixture(shape, 0.0f);
        }

        // Square made from edges notice how the edges are shrunk to account
        // for the polygon radius. This makes it so the square character does
        // not get snagged. However, ray casts can now go through the cracks.
        for (int i = 0; i < 4; i++)
        {
            BodyDef bd = new BodyDef();
            Body ground = _world.CreateBody(bd);
            ground.SetTransform(new Vector2(-2f * i, 0), 0);

            Vector2[] vs = new Vector2[4];
            vs[0] = new Vector2(-1.0f, 3.0f);
            vs[1] = new Vector2(1.0f, 3.0f);
            vs[2] = new Vector2(1.0f, 5.0f);
            vs[3] = new Vector2(-1.0f, 5.0f);
            LoopShape shape = new LoopShape();
            shape._count = 4;
            shape._vertices = vs;
            ground.CreateFixture(shape, 0.0f);

            //PolygonShape shape = new PolygonShape();
            //float d = 2.0f * Settings.b2_polygonRadius;
            //shape.SetAsEdge(new Vector2(-1.0f + d, 3.0f), new Vector2(1.0f - d, 3.0f));
            //ground.CreateFixture(shape, 0.0f);
            //shape.SetAsEdge(new Vector2(1.0f, 3.0f + d), new Vector2(1.0f, 5.0f - d));
            //ground.CreateFixture(shape, 0.0f);
            //shape.SetAsEdge(new Vector2(1.0f - d, 5.0f), new Vector2(-1.0f + d, 5.0f));
            //ground.CreateFixture(shape, 0.0f);
            //shape.SetAsEdge(new Vector2(-1.0f, 5.0f - d), new Vector2(-1.0f, 3.0f + d));
            //ground.CreateFixture(shape, 0.0f);
        }

        // Square character
        {
            BodyDef bd = new BodyDef();
            bd.position = new Vector2(-3.0f, 5.0f);
            bd.type = BodyType.Dynamic;
            bd.fixedRotation = true;
            bd.allowSleep = false;

            Body body = _world.CreateBody(bd);

            PolygonShape shape = new PolygonShape();
            shape.SetAsBox(0.5f, 0.5f);

            FixtureDef fd = new FixtureDef();
            fd.shape = shape;
            fd.density = 20.0f;
            body.CreateFixture(fd);
        }

        #if false
        // Hexagon character
        {
            BodyDef bd = new BodyDef();
            bd.position = new Vector2(-5.0f, 5.0f);
            bd.type = BodyType.Dynamic;
            bd.fixedRotation = true;
            bd.allowSleep = false;

            Body body = _world.CreateBody(bd);

            float angle = 0.0f;
            float delta = (float)Math.PI / 3.0f;
            Vector2[] vertices = new Vector2[6];
            for (int i = 0; i < 6; ++i)
            {
                vertices[i] = new Vector2(0.5f * (float)Math.Cos(angle), 0.5f * (float)Math.Sin(angle));
                angle += delta;
            }

            PolygonShape shape = new PolygonShape();
            shape.Set(vertices, 6);

            FixtureDef fd = new FixtureDef();
            fd.shape = shape;
            fd.density = 20.0f;
            body.CreateFixture(fd);
        }

        // Circle character
        {
            BodyDef bd = new BodyDef();
            bd.position = new Vector2(3.0f, 5.0f);
            bd.type = BodyType.Dynamic;
            bd.fixedRotation = true;
            bd.allowSleep = false;

            Body body = _world.CreateBody(bd);

            CircleShape shape = new CircleShape();
            shape._radius = 0.5f;

            FixtureDef fd = new FixtureDef();
            fd.shape = shape;
            fd.density = 20.0f;
            body.CreateFixture(fd);
        }
        #endif
    }
Exemplo n.º 24
0
        /// <summary>
        /// Create a Box2D body and loads the texture for it
        /// </summary>
        /// <param name="name">Body's textures Content name</param>
        /// <param name="pos">Body's position</param>
        /// <param name="angle">Body's rotation angle</param>
        /// <returns></returns>
        private Body CreateBody(String name, Vector2 pos, float angle)
        {
            BodyDef bodyDef = new BodyDef();
            bodyDef.type = BodyType.Dynamic;
            bodyDef.position = pos;
            bodyDef.position.X /= Level.FACTOR;
            bodyDef.position.Y /= Level.FACTOR;
            bodyDef.angle = angle * Level.DEG_TO_RAD;

            Body body = world.CreateBody(bodyDef);
            Texture2D texture = content.Load<Texture2D>("Images/" + name);
            body.SetUserData(new UserData(name, texture));

            return body;
        }
Exemplo n.º 25
0
    public Tiles()
    {
        {
            float a = 0.5f;
            BodyDef bd = new BodyDef();
            bd.position.Y = -a;
            Body ground = _world.CreateBody(bd);

        #if true
            int N = 200;
            int M = 10;
            Vector2 position = new Vector2();
            position.Y = 0.0f;
            for (int j = 0; j < M; ++j)
            {
                position.X = -N * a;
                for (int i = 0; i < N; ++i)
                {
                    PolygonShape shape = new PolygonShape();
                    shape.SetAsBox(a, a, position, 0.0f);
                    ground.CreateFixture(shape, 0.0f);
                    position.X += 2.0f * a;
                }
                position.Y -= 2.0f * a;
            }
        #else
            int N = 200;
            int M = 10;
            Vector2 position;
            position.x = -N * a;
            for (int i = 0; i < N; ++i)
            {
                position.y = 0.0f;
                for (int j = 0; j < M; ++j)
                {
                    PolygonShape shape = new PolygonShape();
                    shape.SetAsBox(a, a, position, 0.0f);
                    ground.CreateFixture(shape, 0.0f);
                    position.y -= 2.0f * a;
                }
                position.x += 2.0f * a;
            }
        #endif
        }

        {
            float a = 0.5f;
            PolygonShape shape = new PolygonShape();
            shape.SetAsBox(a, a);

            Vector2 x = new Vector2(-7.0f, 0.75f);
            Vector2 y;
            Vector2 deltaX = new Vector2(0.5625f, 1.25f);
            Vector2 deltaY = new Vector2(1.125f, 0.0f);

            for (int i = 0; i < e_count; ++i)
            {
                y = x;

                for (int j = i; j < e_count; ++j)
                {
                    BodyDef bd = new BodyDef();
                    bd.type = BodyType.Dynamic;
                    bd.position = y;
                    Body body = _world.CreateBody(bd);
                    body.CreateFixture(shape, 5.0f);

                    y += deltaY;
                }

                x += deltaX;
            }
        }
    }
Exemplo n.º 26
0
        /// <summary>
        /// Create a rigid body given a definition. No reference to the definition
        /// is retained.
        /// @warning This function is locked during callbacks.
        /// </summary>
        /// <param name="def"></param>
        /// <returns></returns>
        public Body CreateBody(BodyDef def)
        {
            Debug.Assert(!IsLocked);
            if (IsLocked)
            {
                return null;
            }

            var b = new Body(def, this);

            // Add to world doubly linked list.
            b._prev = null;
            b._next = _bodyList;
            if (_bodyList != null)
            {
                _bodyList._prev = b;
            }
            _bodyList = b;
            ++_bodyCount;

            return b;
        }
Exemplo n.º 27
0
        public List<Body> generateLevel()
        {
            String pathToCollisionFile = level.levelConfig.GlobalSection["collision"];

            var vertices = new Vector2[4];

            var startPointsStatic = new List<Vector2>();

            var grays = new List<Vector2>();

            var map = new Bitmap(pathToCollisionFile);

            for (int x = 0; x < map.Size.Width; ++x)
            {
                for (int y = 0; y < map.Size.Height; ++y)
                {
                    var pixel = map.GetPixel(x, y);
                    if (isRed(pixel))
                    {
                        startPointsStatic.Add(new Vector2(x, y));
                    }
                }
            }

            foreach (var startPoint in startPointsStatic)
            {
                vertices = GetVertices(map, startPoint);
                var bodyDef = new BodyDef();
                bodyDef.type = BodyType.Static;

                bodyDef.angle = 0;
                bodyDef.position = level.ConvertToBox2D(startPoint);

                var body = level.World.CreateBody(bodyDef);

                var edges = new List<EdgeInfo>();

                if (vertices.Length < 2)
                {
                    throw new Exception();
                }

                for (int i = 1; i < vertices.Length; ++i)
                {
                    var vertexA = vertices[i - 1];
                    var vertexB = vertices[i];

                    var edgeInfo = new EdgeInfo();
                    edgeInfo.shape = new EdgeShape();
                    edgeInfo.isVertical = vertexA.X == vertexB.X;
                    edgeInfo.shape.Set(vertexA, vertexB);
                    edges.Add(edgeInfo);

                }

                foreach (var edge in edges)
                {
                    var fixture = new FixtureDef();
                    var elementInfo = new LevelElementInfo();
                    fixture.shape = edge.shape;
                    if (edge.isVertical)
                    {
                        fixture.friction = 0.0f;
                        elementInfo.type = LevelElementType.Wall;
                    }
                    else
                    {
                        fixture.friction = level.GroundFriction;
                        elementInfo.type = LevelElementType.Ground;
                    }
                    fixture.userData = elementInfo;
                    body.CreateFixture(fixture);
                }

                bodyList.Add(body);
            }

            return bodyList;
        }
Exemplo n.º 28
0
        public override void Initialize(ConfigSection section)
        {
            base.Initialize(section);

            textureName = section["texture"];
            var pos = section["position"].AsVector2();
            SideLength = section["sideLength"];
            Speed = section["speed"];
            MaxSpeed = section["maxSpeed"];
            JumpImpulse = section["jumpImpulse"];
            JumpThreshold = section["jumpThreshold"];

            var bodyDef = new BodyDef();
            bodyDef.type = BodyType.Dynamic;

            bodyDef.angle = 0;
            bodyDef.position = Game.level.ConvertToBox2D(pos);
            bodyDef.inertiaScale = section["inertiaScale"];
            bodyDef.linearDamping = section["linearDamping"];
            bodyDef.angularDamping = section["angularDamping"];

            bodyDef.userData = this;

            Body = Game.level.World.CreateBody(bodyDef);

            var shape = new PolygonShape();
            var offset = SideLength / 2;
            shape.Set(new Vector2[]{
                Game.level.ConvertToBox2D(new Vector2(-offset, -offset)),
                Game.level.ConvertToBox2D(new Vector2(offset, -offset)),
                Game.level.ConvertToBox2D(new Vector2(offset, offset)),
                Game.level.ConvertToBox2D(new Vector2(-offset, offset))
                }
            , 4);

            var fixture = new FixtureDef();
            fixture.restitution = section["restitution"];
            fixture.density = section["density"];
            fixture.shape = shape;
            fixture.friction = section["friction"];
            Body.CreateFixture(fixture);
        }
Exemplo n.º 29
0
        public override void Initialize(ConfigSection section)
        {
            base.Initialize(section);

            if (section.Options.ContainsKey("texture"))
            {
                _textureName = section["texture"];
            }

            var pos = section["position"].AsVector2();
            _dim = section["dimensions"].AsVector2();

            if (section.Options.ContainsKey("enterEvent"))
            {
                _enterEvent = section["enterEvent"];
            }

            if (section.Options.ContainsKey("leaveEvent"))
            {
                _leaveEvent = section["leaveEvent"];
            }

            if (section.Options.ContainsKey("enterEventData"))
            {
                _enterEventData = section["enterEventData"];
            }

            if (section.Options.ContainsKey("leaveEventData"))
            {
                _leaveEventData = section["leaveEventData"];
            }

            var bodyDef = new BodyDef();
            bodyDef.userData = this;
            var fixtureDef = new FixtureDef();
            var shape = new PolygonShape();
            shape.SetAsBox(Game.level.ConvertToBox2D(_dim.X / 2), Game.level.ConvertToBox2D(_dim.Y / 2));
            fixtureDef.shape = shape;
            fixtureDef.isSensor = true;
            fixtureDef.userData = new LevelElementInfo() { type = LevelElementType.Ground };
            bodyDef.position = Game.level.ConvertToBox2D(pos);
            Body = Game.level.World.CreateBody(bodyDef);
            Body.CreateFixture(fixtureDef);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Creates a new level component
        /// </summary>
        /// <param name="world">The Box2D world that will hold this component</param>
        /// <param name="content">Used ContentManager</param>
        /// <param name="pSpriteBatch">Used SpriteBatch</param>
        /// <param name="pos">The position of the component</param>
        /// <param name="angle">The angle of the component</param>
        /// <param name="pWidth">The width of the component</param>
        /// <param name="pHeight">The height of the component</param>
        public LevelComponent(World world, ContentManager content, 
                              Vector2 pos, float angle, float pWidth, float pHeight)
        {
            Pos = new Vector2();
            x = pos.X;
            y = pos.Y;
            width = pWidth;
            height = pHeight;
            sourceRect = new Rectangle(0, 0, (int)width, (int)height);
            screenPos = new Rectangle(0, 0, (int)width, (int)height);
            origin = new Vector2(sourceRect.Width * 0.5f, sourceRect.Height * 0.5f);

            BodyDef bodyDef = new BodyDef();
            bodyDef.type = BodyType.Static;
            bodyDef.position = pos;
            bodyDef.position.X /= Level.FACTOR;
            bodyDef.position.Y /= Level.FACTOR;
            bodyDef.angle = angle * Level.DEG_TO_RAD;

            body = world.CreateBody(bodyDef);
        }