Esempio n. 1
0
        private void CreateFixture(TmxObject tmxObj)
        {
            float density = 1f;
            string densityStr;
            tmxObj.Properties.TryGetValue("Density", out densityStr);
            if (densityStr != null)
            {
                density = float.Parse(densityStr);
            }

            // A Farseer Body's Position variable defines the CENTER of the Body, so we add half the width and height to get it to the desired location.
            switch (tmxObj.ObjectType)
            {
                case TmxObjectType.Basic:
                case TmxObjectType.Tile:
                    {
                        Vector2 size = ConvertUnits.ToSimUnits(new Vector2((float)tmxObj.Width, (float)tmxObj.Height));
                        fixture = FixtureFactory.AttachRectangle(size.X, size.Y, density, Vector2.Zero, body);
                        break;
                    }
                case TmxObjectType.Ellipse:
                    {
                        Vector2 size = ConvertUnits.ToSimUnits(new Vector2((float)tmxObj.Width, (float)tmxObj.Height));
                        if (size.X == size.Y)
                        {
                            fixture = FixtureFactory.AttachCircle(size.X / 2, density, body);
                        }
                        else
                        {
                            fixture = FixtureFactory.AttachEllipse(size.X / 2, size.Y / 2, Settings.MaxPolygonVertices, density, body);
                        }
                        break;
                    }
                case TmxObjectType.Polygon:
                    {
                        Vertices vertices = new Vertices();
                        foreach (var v in tmxObj.Points)
                        {
                            vertices.Add(ConvertUnits.ToSimUnits(new Vector2((float)v.X, (float)v.Y)));
                        }
                        List<Vertices> decomposedVertices = Triangulate.ConvexPartition(vertices, TriangulationAlgorithm.Bayazit);
                        fixtures = FixtureFactory.AttachCompoundPolygon(decomposedVertices, density, body);
                        break;
                    }
                case TmxObjectType.Polyline:
                    {
                        Vertices vertices = new Vertices();
                        foreach (var v in tmxObj.Points)
                        {
                            vertices.Add(ConvertUnits.ToSimUnits(new Vector2((float)v.X, (float)v.Y)));
                        }
                        fixture = FixtureFactory.AttachChainShape(vertices, body);
                        break;
                    }
                default:
                    {
                        throw new InvalidOperationException("TmxObjectType not recognized: " + tmxObj.ObjectType.ToString());
                    }
            }
        }
Esempio n. 2
0
        internal override void start()
        {
            float angle = (float)gameObject.angle;

            if (vertices.Count <= 1)
            {
                vertices.Add(new Vector(0, 0));
                vertices.Add(new Vector(10, 0));
                vertices.Add(new Vector(10, 10));
                vertices.Add(new Vector(0, 10));
            }

            Vertices vrts = new Vertices();

            for (int i = 0; i < vertices.Count; i++)
            {
                vrts.Add(new Vector2((float)vertices[i].x, (float)vertices[i].y));
            }

            _vertices = FarseerPhysics.Common.Decomposition.Triangulate.ConvexPartition(vrts, TriangulationAlgorithm.Bayazit);

            body = new Body(Engine.world, new Vector2((float)gameObject.position.x, (float)gameObject.position.y), (float)Mathf.toRadians(angle), FarseerPhysics.Dynamics.BodyType.Dynamic, null);
            setBodyType(bodyType);
            fixture = FixtureFactory.AttachCompoundPolygon(_vertices, 1.0f, body);

            body.AngularDamping = _angularDamping;
            body.Enabled        = _enabled;
            body.FixedRotation  = _fixedRotation;
            body.Friction       = _friction;
            body.LinearDamping  = _linearDamping;

            body.OnCollision += body_OnCollision;
        }
Esempio n. 3
0
        static private void CreateShape(SFML.Graphics.Texture texture, World world)
        {
            // Make collision Geo from bitmap
            // Get pixel data in array​
            byte[] bytes = texture.CopyToImage().Pixels;
            uint[] data  = new uint[texture.Size.X * texture.Size.Y];
            for (int i = 0; i < bytes.Length; i += 4)
            {
                data[i / 4] = BitConverter.ToUInt32(bytes, i);
            }

            Byte myByte = 1;

            List <Vertices> _list = PolygonTools.CreatePolygon(data, (int)texture.Size.X, 0.05f, myByte, true, true);
            Vertices        verts = new Vertices();
            Vector2         scale = ConvertUnits.ToSimUnits(new Vector2(1, 1));

            foreach (Vertices v in _list)
            {
                v.Scale(scale);
                //    v.Translate(ConvertUnits.ToSimUnits(new Vector2(-16, -16)));
                Body body = new Body(world);
                body.SleepingAllowed = false;
                body.UserData        = "wall";
                List <Fixture> fixtures = FixtureFactory.AttachCompoundPolygon(
                    FarseerPhysics.Common.Decomposition.Triangulate.ConvexPartition(SimplifyTools.DouglasPeuckerSimplify(v, 0.05f), TriangulationAlgorithm.Bayazit, false, 0.05f),
                    1, body);
            }
        }
Esempio n. 4
0
        public void AttachToBody(Body body, Vector2 scale)
        {
            float scaleD = (scale.X + scale.Y) / 2f;

            switch (Type)
            {
            case ShapeType.Circle:
                FixtureFactory.AttachCircle(UnitsConverter.ToSimUnits(XRadius) * scaleD, Density, body);
                break;

            case ShapeType.Ellipse:
                FixtureFactory.AttachEllipse(UnitsConverter.ToSimUnits(XRadius) * scale.X, UnitsConverter.ToSimUnits(YRadius) * scale.Y, Edges, Density, body);
                break;

            case ShapeType.Edge:
                FixtureFactory.AttachEdge(UnitsConverter.ToSimUnits(Start) * scale, UnitsConverter.ToSimUnits(End) * scale, body);
                break;

            case ShapeType.Rectangle:
                FixtureFactory.AttachRectangle(UnitsConverter.ToSimUnits(Width) * scale.X, UnitsConverter.ToSimUnits(Height) * scale.Y, Density, UnitsConverter.ToSimUnits(Offset) * scale, body);
                break;

            case ShapeType.Polygon:

                Vertices p = new Vertices();
                foreach (Vector2 node in Polygon[0])
                {
                    p.Add(UnitsConverter.ToSimUnits(node) * scale);
                }

                FixtureFactory.AttachPolygon(p, Density, body);
                break;

            case ShapeType.CompoundPolygon:

                List <Vertices> cp = new List <Vertices>();
                foreach (Vertices v in Polygon)
                {
                    Vertices polygon = new Vertices();
                    foreach (Vector2 node in v)
                    {
                        polygon.Add(UnitsConverter.ToSimUnits(node) * scale);
                    }
                    cp.Add(polygon);
                }

                FixtureFactory.AttachCompoundPolygon(cp, Density, body);
                break;

            default:
                return;
            }
        }
Esempio n. 5
0
        public static List <Fixture> AttachCompoundPolygon(this Body body, List <Vertices> list, float density)
        {
            for (var i = 0; i < list.Count; i++)
            {
                var vertices = list[i];
                for (var j = 0; j < vertices.Count; j++)
                {
                    vertices[j] = FSConvert.DisplayToSim * vertices[j];
                }
            }

            return(FixtureFactory.AttachCompoundPolygon(list, density, body));
        }
Esempio n. 6
0
        internal static void AddMesh(Body body, bool isTrigger, List <Vertices> tris, float density)
        {
            if (world == null)
            {
                throw new InvalidOperationException("You have to Initialize the Physics system before adding bodies");
            }
            List <Fixture> fixes = FixtureFactory.AttachCompoundPolygon(tris, density, body);

            for (int i = 0; i < fixes.Count; i++)
            {
                fixes[i].IsSensor = isTrigger;
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Converts image data to physics fixtures, and initializes default values
        /// </summary>
        public virtual void InitializePhysics()
        {
            Body          = new Body(game.Physics);
            Body.UserData = this;

            PhysicsFrame easyVertices = PhysicsHelper.GetVerticesForTexture(texture);

            FixtureFactory.AttachCompoundPolygon(easyVertices.Vertices, 1f, Body);
            offset = easyVertices.Offset;

            Body.Mass = 1f;

            PhysicsHelper.AttachOnCollisionHandlers(Body, game);
        }
Esempio n. 8
0
        public override void InitializePhysics()
        {
            Body               = new Body(game.Physics);
            Body.UserData      = this;
            Body.BodyType      = BodyType.Dynamic;
            Body.FixedRotation = true;
            frames             = new List <PhysicsFrame>();

            PhysicsFrame   frame    = PhysicsHelper.GetVerticesForTexture(spriteSheet, 0);
            List <Fixture> fixtures = FixtureFactory.AttachCompoundPolygon(frame.Vertices, 1f, Body);

            frame.Fixtures = fixtures;
            frames.Add(frame);
            PhysicsHelper.AttachOnCollisionHandlers(Body, game);
        }
Esempio n. 9
0
        /// <summary>
        /// Luo uuden fysiikkaolion.
        /// </summary>
        /// <param name="width">Leveys.</param>
        /// <param name="height">Korkeus.</param>
        /// <param name="shape">Muoto.</param>
        /// <param name="world">Fysiikkamoottorin maailma johon kappale luodaan.</param>
        public PhysicsBody(double width, double height, Shape shape, World world)
        {
            this._size  = new Vector(width, height) * FSConvert.DisplayToSim;
            this._shape = shape;

            FSBody         = world.CreateBody(bodyType: BodyType.Dynamic);// BodyFactory.CreateBody(world, bodyType: BodyType.Dynamic);
            FSBody.owner   = this;
            FSBody.Enabled = false;
            if (shape is Ellipse && width == height)
            {
                Fixture f = FixtureFactory.AttachCircle((float)height * FSConvert.DisplayToSim / 2, DefaultDensity, FSBody);
                f.Tag = FSBody;
            }
            else
            {
                List <Vertices> vertices = CreatePhysicsShape(shape, this._size);
                List <Fixture>  fixtures = FixtureFactory.AttachCompoundPolygon(vertices, DefaultDensity, FSBody);
                fixtures.ForEach((f) => f.Tag = FSBody);
            }
        }
Esempio n. 10
0
        private void MakePolygon()
        {
            Vector2 avgLoc = new Vector2();

            foreach (Vector2 vert in polyPoints)
            {
                avgLoc += vert;
            }
            avgLoc /= polyPoints.Count;



            Vertices verts = new Vertices();

            foreach (Vector2 v in polyPoints)
            {
                verts.Add(v - avgLoc);
            }

            Body           b           = new Body(game.farseerManager.world);
            List <Fixture> composition = FixtureFactory.AttachCompoundPolygon(EarclipDecomposer.ConvexPartition(verts), 1, b);

            b.Position = avgLoc;

            foreach (Fixture triangle in composition)
            {
                FarseerTextures.ApplyTexture(triangle, FarseerTextures.TextureType.Normal);
            }

            if (composition.Count > 0)
            {
                FormManager.Property.setPendingObjects(new List <object>()
                {
                    composition[0].Body
                });
            }

            polyPoints.Clear();
        }
Esempio n. 11
0
        private void CreateLeg(float s, FVector2 wheelAnchor)
        {
            FVector2 p1, p2, p3, p4, p5, p6;

            p1 = new FVector2((162f * s) / tScale, -183f / tScale);
            p2 = new FVector2((216f * s) / tScale, -36f / tScale);
            p3 = new FVector2((129f * s) / tScale, -57f / tScale);
            p4 = new FVector2((093f * s) / tScale, 24f / tScale);
            p5 = new FVector2((180f * s) / tScale, 45f / tScale);
            p6 = new FVector2((075f * s) / tScale, 111f / tScale);

            Body body1;
            Body body2;

            body1          = BodyFactory.CreateBody(FSWorldComponent.PhysicsWorld, m_offset);
            body1.BodyType = BodyType.Dynamic;
            body2          = BodyFactory.CreateBody(FSWorldComponent.PhysicsWorld, FVector2.Add(p4, m_offset));
            body2.BodyType = BodyType.Dynamic;

            Fixture b1fix;
            Fixture b2fix;

            List <Vertices> vl1 = new List <Vertices>();
            List <Vertices> vl2 = new List <Vertices>();

            vl1.Add(new Vertices());
            vl2.Add(new Vertices());

            if (s > 0f)
            {
                vl1[0].Add(p1);
                vl1[0].Add(p2);
                vl1[0].Add(p3);
                vl2[0].Add(FVector2.Zero);
                vl2[0].Add(FVector2.Subtract(p5, p4));
                vl2[0].Add(FVector2.Subtract(p6, p4));
            }
            else
            {
                vl1[0].Add(p1);
                vl1[0].Add(p3);
                vl1[0].Add(p2);
                vl2[0].Add(FVector2.Zero);
                vl2[0].Add(FVector2.Subtract(p6, p4));
                vl2[0].Add(FVector2.Subtract(p5, p4));
            }

            b1fix = FixtureFactory.AttachCompoundPolygon(vl1, 1f, body1)[0];
            b2fix = FixtureFactory.AttachCompoundPolygon(vl2, 1f, body2)[0];
            b1fix.CollisionCategories = Category.Cat10;
            b1fix.CollidesWith        = Category.Cat1;
            b2fix.CollisionCategories = Category.Cat10;
            b2fix.CollidesWith        = Category.Cat1;

            body1.AngularDamping = 10f;
            body2.AngularDamping = 10f;

            DistanceJoint dj;
            float         dampingRatio = 0.5f;
            float         freqHz       = 10f;

            // Using a soft distance constraint can reduce some jitter.
            // It also makes the structure seem a bit more fluid by
            // acting like a suspension system.

            dj = JointFactory.CreateDistanceJoint(FSWorldComponent.PhysicsWorld, body1, body2, body1.GetLocalPoint(FVector2.Add(p2, m_offset)), body2.GetLocalPoint(FVector2.Add(p5, m_offset)));
            dj.DampingRatio = dampingRatio;
            dj.Frequency    = freqHz;

            dj = JointFactory.CreateDistanceJoint(FSWorldComponent.PhysicsWorld, body1, body2, body1.GetLocalPoint(FVector2.Add(p3, m_offset)), body2.GetLocalPoint(FVector2.Add(p4, m_offset)));
            dj.DampingRatio = dampingRatio;
            dj.Frequency    = freqHz;

            dj = JointFactory.CreateDistanceJoint(FSWorldComponent.PhysicsWorld, body1, m_wheel, body1.GetLocalPoint(FVector2.Add(p3, m_offset)), m_wheel.GetLocalPoint(FVector2.Add(wheelAnchor, m_offset)));
            dj.DampingRatio = dampingRatio;
            dj.Frequency    = freqHz;

            dj = JointFactory.CreateDistanceJoint(FSWorldComponent.PhysicsWorld, body2, m_wheel, body2.GetLocalPoint(FVector2.Add(p6, m_offset)), m_wheel.GetLocalPoint(FVector2.Add(wheelAnchor, m_offset)));
            dj.DampingRatio = dampingRatio;
            dj.Frequency    = freqHz;

            JointFactory.CreateRevoluteJoint(FSWorldComponent.PhysicsWorld, body2, m_chassis, m_chassis.GetLocalPoint(FVector2.Add(p4, m_offset)));
        }
Esempio n. 12
0
    public void setup_with_body(FlatBodyObject aBody, bool aUseGravity = true)
    {
        mFlat = aBody;
        //construct the bodies
        foreach (var e in mImportant)
        {
            //note this will cerate 'dummy bodies' representing hand/ankle/head
            BodyGroup bg = new BodyGroup();
            bg.offset             = aBody.mParts[e.Key].transform.rotation.flat_rotation();
            bg.body               = BodyFactory.CreateBody(FSWorldComponent.PhysicsWorld, mFlat.mParts[e.Key].transform.position.toFV2());
            bg.body.Mass          = 25;
            bg.body.Friction      = .5f;
            bg.body.IgnoreGravity = !aUseGravity;
            bg.body.BodyType      = FarseerPhysics.Dynamics.BodyType.Dynamic;
            mBodies[e.Key]        = bg;

            //TODO why do I still have this? can probably delete
            //new GameObject(e.Key.ToString()).transform.position = mFlat.mParts[e.Key].transform.position;
        }

        //now create fixtures
        foreach (var e in mImportant)
        {
            if (e.Value.otherEnds.Count > 0)
            {
                List <FarseerPhysics.Common.Vertices> poly = new List <FarseerPhysics.Common.Vertices>();
                poly.Add(new FarseerPhysics.Common.Vertices());
                if (e.Key != ZgJointId.Torso || e.Value.otherEnds.Count == 1)                //torso does not need this point
                {
                    poly[0].Add(FVector2.Zero);
                }
                if (e.Value.otherEnds.Count == 1)
                {
                    //line version
                    //foreach(var f in e.Value.otherEnds)
                    //	poly[0].Add(mFlat.mParts[f].transform.position.toFV2()-mBodies[e.Key].body.Position);

                    //block version
                    FVector2 diff = mFlat.mParts[e.Value.otherEnds[0]].transform.position.toFV2() - mBodies[e.Key].body.Position;
                    FVector2 perp = new FVector2(diff.Y, -diff.X);
                    perp.Normalize();
                    float stretch = .03f;
                    poly[0].Add(perp * stretch);
                    poly[0].Add(diff + perp * stretch);
                    poly[0].Add(diff - perp * stretch);
                    poly[0].Add(-perp * stretch);
                }
                else
                {
                    foreach (var f in e.Value.otherEnds)
                    {
                        poly[0].Add(mFlat.mParts[f].transform.position.toFV2() - mBodies[e.Key].body.Position);
                    }
                }
                var fixture = FixtureFactory.AttachCompoundPolygon(poly, 1, mBodies[e.Key].body);
                fixture[0].CollisionGroup = -8; //negative indices never self collide
            }
        }

        //create joints
        foreach (var e in mImportant)
        {
            foreach (var f in e.Value.otherEnds)
            {
                if (mImportant[f].otherEnds.Count > 0)
                {
                    var joint = JointFactory.CreateRevoluteJoint(FSWorldComponent.PhysicsWorld, mBodies[e.Key].body, mBodies[f].body, FVector2.Zero);
                    mBodies[f].joint = joint;
                }
            }
        }

        //clean up the dummy bodies
        foreach (var e in mImportant)
        {
            if (e.Value.otherEnds.Count == 0)
            {
                FSWorldComponent.PhysicsWorld.RemoveBody(mBodies[e.Key].body);
                mBodies.Remove(e.Key);
            }
        }
    }
Esempio n. 13
0
        private void CreatePreview()
        {
            if (materialBox.SelectedItem != null && colorBox.SelectedItem != null && shapeBox.SelectedItem != null)
            {
                Dictionary <string, object> shapeParameters = new Dictionary <string, object>();
                shapeParameters.Add(ShapeParametersKeys.Material, materialBox.SelectedItem.ToString());
                shapeParameters.Add(ShapeParametersKeys.MaterialScale, float.Parse(materialScale.Value.ToString()));
                shapeParameters.Add(ShapeParametersKeys.Color, _colorDictionary[colorBox.SelectedItem.ToString()]);

                ObjectType objectType = (ObjectType)Enum.Parse(typeof(ObjectType), shapeBox.SelectedItem.ToString());
                shapeParameters.Add(ShapeParametersKeys.ObjectType, objectType);
                switch (objectType)
                {
                case ObjectType.Arc:
                    shapeParameters.Add(ShapeParametersKeys.ArcDegrees, float.Parse(arcDegrees.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.ArcRadius, float.Parse(arcRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.ArcSides, int.Parse(arcSides.Value.ToString()));
                    break;

                case ObjectType.Capsule:
                    shapeParameters.Add(ShapeParametersKeys.CapsuleHeight, float.Parse(capsuleHeight.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.CapsuleBottomRadius, float.Parse(capsuleBottomRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.CapsuleBottomEdges, int.Parse(capsuleBottomEdges.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.CapsuleTopRadius, float.Parse(capsuleTopRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.CapsuleTopEdges, int.Parse(capsuleTopEdges.Value.ToString()));
                    break;

                case ObjectType.Gear:
                    shapeParameters.Add(ShapeParametersKeys.GearRadius, float.Parse(gearRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.GearNumberOfTeeth, int.Parse(gearNumberOfTeeth.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.GearTipPercentage, float.Parse(gearTipPercentage.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.GearToothHeigt, float.Parse(gearToothHeight.Value.ToString()));
                    break;

                case ObjectType.Rectangle:
                    shapeParameters.Add(ShapeParametersKeys.RectangleWidth, float.Parse(rectangleWidth.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.RectangleHeight, float.Parse(rectangleHeight.Value.ToString()));
                    break;

                case ObjectType.RoundedRectangle:
                    shapeParameters.Add(ShapeParametersKeys.RoundedRectangleHeight, float.Parse(roundedRectangleWidth.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.RoundedRectangleWidth, float.Parse(roundedRectangleHeight.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.RoundedRectangleXRadius, float.Parse(roundedRectangleXRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.RoundedRectangleYRadius, float.Parse(roundedRectangleYRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.RoundedRectangleSegments, int.Parse(roundedRectangleSegments.Value.ToString()));
                    break;

                case ObjectType.Ellipse:
                    shapeParameters.Add(ShapeParametersKeys.EllipseXRadius, float.Parse(ellipseXRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.EllipseYRadius, float.Parse(ellipseYRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.EllipseNumberOfEdges, int.Parse(ellipseNumberOfEdges.Value.ToString()));
                    break;

                case ObjectType.Circle:
                    shapeParameters.Add(ShapeParametersKeys.CircleRadius, float.Parse(circleRadius.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.CircleSegments, AssetCreator.CircleSegments);
                    break;

                case ObjectType.CustomShape:
                    if (shapeFromTextureBox.SelectedItem == null)
                    {
                        return;
                    }
                    shapeParameters.Add(ShapeParametersKeys.CustomObjectScale, float.Parse(customShapeScale.Value.ToString()));
                    shapeParameters.Add(ShapeParametersKeys.CustomObjectShape, shapeFromTextureBox.SelectedItem.ToString());
                    shapeParameters.Add(ShapeParametersKeys.CustomObjectUseOriginalTexture, useOriginalTextureCheck.Checked);
                    break;

                default:
                    throw new Exception("Unknown Shape");
                }

                //Сохраняем исходную текстуру в словарь метаданных
                switch (objectType)
                {
                case ObjectType.CustomShape:
                    shapeParameters.Add(ShapeParametersKeys.Texture, _assetCreator.GetShape((string)shapeParameters[ShapeParametersKeys.CustomObjectShape]));
                    break;

                default:
                    shapeParameters.Add(ShapeParametersKeys.Texture, _assetCreator.GetMaterial((string)shapeParameters[ShapeParametersKeys.Material]));
                    break;
                }

                Vertices  shapeVertices;
                Texture2D previewTexture;
                TextureFromDictionary(shapeParameters, out previewTexture, out shapeVertices);
                if (shapeVertices != null && previewTexture != null)
                {
                    float?previousDensity = _objectLevelManager.PreviewObject[0].Body.Density;

                    _objectLevelManager.PreviewObject[0].Body.FixtureList.Clear();

                    switch ((ObjectType)Enum.Parse(typeof(ObjectType), shapeBox.SelectedItem.ToString()))
                    {
                    case ObjectType.Circle:
                        FixtureFactory.AttachCircle(float.Parse(circleRadius.Value.ToString()), previousDensity == null ? 1f : (float)previousDensity, _objectLevelManager.PreviewObject[0].Body);
                        break;

                    default:
                        FixtureFactory.AttachCompoundPolygon(BayazitDecomposer.ConvexPartition(shapeVertices),
                                                             previousDensity == null ? 1f : (float)previousDensity,
                                                             _objectLevelManager.PreviewObject[0].Body);
                        break;
                    }
                    _objectLevelManager.PreviewObject[0].Sprites[0] = new Sprite(previewTexture);

                    _objectLevelManager.PreviewVertices = shapeVertices;

                    previewScreen.PreviewGameObject = _objectLevelManager.PreviewObject[0];


                    editCurrentObjectAction.Checked = true;
                    SetMouseToolButtonsState(editCurrentObjectAction);
                }

                previewTexture.SetMetadataDictionary(shapeParameters);
            }
        }
Esempio n. 14
0
        public override void LoadContent()
        {
            base.LoadContent();

            Game.EngineComponents.Get <AudioManager>().PreloadSoundEffects("Audio/countDownLong", "Audio/countDownShort");

            Game.CurrentGameMode.ClearScore();

            AddPlayersWithBarns(locs, rotations);

            // Border trees
            Entity border;

            AddEntity(border = new Entity(this, EntityType.Game, new Vector2(0, 0),
                                          new SpriteComponent("joinscreen_outerBorder", new Vector2(screenWidth, screenWidth / 3.84f * 2.245f), new Vector2(0.5f, 0.5f), layerDepth: 0.9f)
                                          ));

            var triangulated = Triangulate.ConvexPartition(GameConstants.BoundingGameFieldTop, TriangulationAlgorithm.Earclip);

            triangulated.AddRange(Triangulate.ConvexPartition(GameConstants.BoundingGameFieldRight, TriangulationAlgorithm.Earclip));
            triangulated.AddRange(Triangulate.ConvexPartition(GameConstants.BoundingGameFieldBottom, TriangulationAlgorithm.Earclip));
            triangulated.AddRange(Triangulate.ConvexPartition(GameConstants.BoundingGameFieldLeft, TriangulationAlgorithm.Earclip));
            var fixtureList = FixtureFactory.AttachCompoundPolygon(triangulated, 1, border.Body);

            border.AddComponent(new PhysicsComponent(fixtureList[0].Shape));

            // Background
            AddEntity(new Entity(this, EntityType.Game, new Vector2(0, 0),
                                 // src image 6000x3508
                                 new SpriteComponent("background", new Vector2(screenWidth, screenWidth / 3.84f * 2.245f), new Vector2(0.5f, 0.5f), layerDepth: -1.0f)
                                 ));


            // HUD
            // src image 1365x460
            if (spawnAnyUI)
            {
                timeComponentBackground = new HUDComponent("timer_bg", new Vector2(1.365f / 0.46f * 0.1f, 1f * 0.1f), new Vector2(0.5f, 0f));

                this.timeComponent100 = new HUDTextComponent(MainFont, 0.07f, "", color: countdownColor,
                                                             offset: timeComponentBackground.LocalPointToWorldPoint(new Vector2(0.35f, 0.5f)),
                                                             origin: new Vector2(0.5f, 0.5f)
                                                             );
                this.timeComponent10 = new HUDTextComponent(MainFont, 0.07f, "", color: countdownColor,
                                                            offset: timeComponentBackground.LocalPointToWorldPoint(new Vector2(0.425f, 0.5f)),
                                                            origin: new Vector2(0.5f, 0.5f)
                                                            );
                this.timeComponent1 = new HUDTextComponent(MainFont, 0.07f, "", color: countdownColor,
                                                           offset: timeComponentBackground.LocalPointToWorldPoint(new Vector2(0.5f, 0.5f)),
                                                           origin: new Vector2(0.5f, 0.5f)
                                                           );
                AddEntity(new Entity(this, EntityType.UI, new Vector2(0.5f, 0f),
                                     timeComponentBackground, timeComponent100, timeComponent10, timeComponent1
                                     ));

                if (!IsCountdownRunning)
                {
                    timeComponentBackground.Opacity    =
                        timeComponent100.Opacity       =
                            timeComponent10.Opacity    =
                                timeComponent1.Opacity = 0f;
                }

                UpdateCountdown(0);

                // Add pause overlay
                AddEntity(new Entity(this, EntityType.UI, pauseOverlayComponents.AddAndReturn(new HUDComponent(Game.Debug.DebugRectangle, Vector2.One, layerDepth: 0.99f)
                {
                    Color = Color.Black,
                    MaintainAspectRation = false,
                    OnVirtualUIScreen    = false,
                })));

                AddEntity(new Entity(this, EntityType.UI, new Vector2(0.5f, 0.25f),
                                     pauseTextOverlayComponents.AddAndReturn(new HUDTextComponent(MainFont, 0.2f, "Game Paused", origin: new Vector2(0.5f, 0.5f), layerDepth: 1f))));

                pauseTextOverlayComponents.AddRange(
                    AddEntity(pauseMenuList = new HUDListEntity(this, new Vector2(0.5f, 0.5f), layerDepth: 1f,
                                                                menuEntries: new[] { new HUDListEntity.ListEntry("Resume", TogglePause), new HUDListEntity.ListEntry("Rejoin", BackToJoinScreen)
                                                                                     , new HUDListEntity.ListEntry("Back to main menu", BackToMainMenu) })
                {
                    Enabled = false
                })
                    .GetAllComponents <HUDTextComponent>().ToList());

                // make overlay invisible
                // [FOREACH PERFORMANCE] Should not allocate garbage
                pauseOverlayComponents.ForEach(c => c.Opacity = 0f);
                // [FOREACH PERFORMANCE] Should not allocate garbage
                pauseTextOverlayComponents.ForEach(c => c.Opacity = 0f);

                // Add pause controls
                // [FOREACH PERFORMANCE] Should not allocate garbage
                foreach (var playerInfo in Game.CurrentGameMode.PlayerInfos)
                {
                    if (playerInfo.IsKeyboardPlayer)
                    {
                        AddEntity(new Entity(this, EntityType.LayerIndependent, new InputComponent(new InputMapping(i => InputFunctions.KeyboardPause(i), (f) => TogglePause(null)))));
                    }
                    else
                    {
                        AddEntity(new Entity(this, EntityType.LayerIndependent, new InputComponent(playerInfo.GamepadIndex,
                                                                                                   new InputMapping(i => InputFunctions.Pause(i), (f) => TogglePause(null)),
                                                                                                   new InputMapping(i => InputFunctions.StartCountdown(i), (f) => StartCountown())
                                                                                                   )));
                    }
                }

                var playerInfos = Game.CurrentGameMode.PlayerInfos;
                var colors      = ((PlayerColors[])Enum.GetValues(typeof(PlayerColors)));

                initialCountdownComponent = new HUDTextComponent(MainFont, 0.25f, Game.CurrentGameMode.PlayerMode == PlayerMode.TwoVsTwo ? "vs" : "free4all", origin: new Vector2(0.5f, 0.5f));
                playerName1Component      = new HUDTextComponent(MainFont, 0.15f, playerInfos[0].Name, color: colors[0].GetColor(), origin: new Vector2(0f, 0.5f), offset: new Vector2(-0.25f, -0.25f));
                playerName2Component      = new HUDTextComponent(MainFont, 0.15f, playerInfos.Count > 1 ? playerInfos[1].Name : "name2", color: colors[1].GetColor(), origin: new Vector2(0f, 0.5f), offset: new Vector2(-0.25f, 0.25f));
                playerName3Component      = new HUDTextComponent(MainFont, 0.15f, playerInfos.Count > 2 ? playerInfos[2].Name : "name3", color: colors[2].GetColor(), origin: new Vector2(1f, 0.5f), offset: new Vector2(0.25f, -0.25f));
                playerName4Component      = new HUDTextComponent(MainFont, 0.15f, playerInfos.Count > 3 ? playerInfos[3].Name : "name4", color: colors[3].GetColor(), origin: new Vector2(1f, 0.5f), offset: new Vector2(0.25f, 0.25f));
                separatorTeam1Component   = new HUDTextComponent(MainFont, 0.15f, "&", origin: new Vector2(0.5f, 0.5f), offset: new Vector2(0f, -0.25f));
                separatorTeam2Component   = new HUDTextComponent(MainFont, 0.15f, "&", origin: new Vector2(0.5f, 0.5f), offset: new Vector2(0f, 0.25f));
                Entity countdownEntity;
                AddEntity(countdownEntity = new Entity(this, EntityType.UI, new Vector2(0.5f, 0.5f), initialCountdownComponent));

                if (Game.CurrentGameMode.PlayerMode == PlayerMode.TwoVsTwo)
                {
                    countdownEntity.AddComponent(playerName1Component);
                    countdownEntity.AddComponent(playerName2Component);
                    countdownEntity.AddComponent(playerName3Component);
                    countdownEntity.AddComponent(playerName4Component);
                    countdownEntity.AddComponent(separatorTeam1Component);
                    countdownEntity.AddComponent(separatorTeam2Component);
                }
            }
            // Camera director
            AddEntity(new Entity(this, EntityType.LayerIndependent, new CameraDirectorComponent(playerEntities, Game.Camera)));
        }