Exemplo n.º 1
0
        public static Dictionary <string, BodyTemplate> LoadBodies(string xml)
        {
            Dictionary <string, BodyTemplate> results = new Dictionary <string, BodyTemplate>();

            XDocument bodyXml = XDocument.Parse(xml);

            float ptm = 1f / (float)Convert.ToDouble(bodyXml.XPathSelectElement("bodydef/metadata/ptm_ratio").Value);

            World world = new World();

            var xmlBodies = bodyXml.XPathSelectElements("bodydef/bodies/body");

            foreach (var xmlBody in xmlBodies)
            {
                var bodyName = xmlBody.Attribute("name").Value;

                BodyTemplate body = new BodyTemplate();
                results.Add(bodyName, body);

                var xmlFixtures = xmlBody.XPathSelectElements("fixtures/fixture");
                foreach (var xmlFixture in xmlFixtures)
                {
                    float density = (float)Convert.ToDouble(xmlFixture.XPathSelectElement("density").Value);

                    var xmlPolygons = xmlFixture.XPathSelectElements("polygons/polygon");
                    foreach (var xmlPolygon in xmlPolygons)
                    {
                        Vertices     vertices = new Vertices();
                        List <float> values   = xmlPolygon.Value.Split(',')
                                                .Select(x => (float)Convert.ToDouble(x.Trim())).ToList();

                        for (int i = 0; i < values.Count; i += 2)
                        {
                            vertices.Add(new Vector2(values[i], values[i + 1]) * ptm);
                        }

                        PolygonShape polygon = new PolygonShape(vertices, density);

                        FixtureTemplate fixture = new FixtureTemplate();
                        fixture.Shape = polygon;
                        body.Fixtures.Add(fixture);
                        body.Mass = 1;
                    }
                }

                var actualBody = body.Create(world);
                actualBody.BodyType = BodyType.Dynamic;
                foreach (var fixture in body.Fixtures)
                {
                    var polygon = (PolygonShape)fixture.Shape;
                    polygon.Vertices.Translate(-actualBody.LocalCenter);
                }
            }

            return(results);
        }
Exemplo n.º 2
0
        public CastRef <PhysicsObject> SetupPhysicsObject(PhysicsObject physicsObject, BodyTemplate bodyTemplate)
        {
            var body = bodyTemplate.Create(physicsWorld);

            body.BodyType        = BodyType.Dynamic;
            body.SleepingAllowed = false;

            physicsObject.Body = body;


            var entityRef = SetupGameObject(physicsObject);
            var poRef     = new CastRef <PhysicsObject>(entityRef);

            poRef.EntityRef.RegisterRemovedCallback(PhysicsObjectDestroyed);

            physicsObjects.Add(poRef);

            return(poRef);
        }