Search code examples
c#xnagame-physicsfarseer

How can I create polygons in Farseer?


I always get many error messages when I want to create polygons in Farseer.

'FarseerPhysics.Common.Vertices' does not contain a definition for 'CreatePolygon' 'FarseerPhysics.Factories.BodyFactory' does not contain a definition for 'Instance' The name 'physicsSimulator' does not exist in the current context The name 'triangleGeomtry' does not exist in the current context The name 'GeomFactory' does not exist in the current context The name 'physicsSimulator' does not exist in the current context

What is wrong? How can I create polygons in Farseer?

        triangleSprite = Content.Load<Texture2D>("triangle"); // Load the Sprite
        data = new uint[triangleSprite.Width * triangleSprite.Height]; 
        triangleSprite.GetData(data);
        verts = Vertices.CreatePolygon(data, triangleSprite.Width, triangleSprite.Height); 
        polygonOrigin = verts.GetCentroid(); 
        triangleBody = BodyFactory.Instance.CreatePolygonBody(physicsSimulator, verts, 3);
        triangleBody.Position = new Vector2(400, 600);
        triangleGeomtry = GeomFactory.Instance.CreatePolygonGeom(physicsSimulator, triangleBody, verts, 0);

Solution

  • Heres how I'm doing it.. Using XNA 4 and Farseer 3.3.1

            //List of vectors defining my custom poly
            Vector2[] vlist = 
                {
                    ConvertUnits.ToSimUnits(new Vector2(25,0)) 
                    ,ConvertUnits.ToSimUnits(new Vector2(15,25)) 
                    ,ConvertUnits.ToSimUnits(new Vector2(-15,25)) 
                    ,ConvertUnits.ToSimUnits(new Vector2(-25,0))
                    ,ConvertUnits.ToSimUnits(new Vector2(-15,-10))
                    ,ConvertUnits.ToSimUnits(new Vector2(15,-10))
                };
    
            //get farseer 'vertices' from vectors
            Vertices _shapevertices = new Vertices(vlist);
    
            //feed vertices array to BodyFactory.CreatePolygon to get a new farseer polygonal body
            _newBody = BodyFactory.CreatePolygon(_world, _shapevertices, _stats.Density);
    

    I'm defining the shape myself but I know farseer has tools included that will give you the 'vertices' object based on a sprite if you want to do that.

    The texture to polygon section here runs through how to do that.