Texture to Polygon: Varying results

Oct 13, 2011 at 12:25 AM
Edited Oct 13, 2011 at 4:30 AM

I'm trying to get Texture to Polygon to work so that I can have hand-drawn levels, and I'm having a bit of trouble with aligning the bodies to the visible textures. It always creates the body shape from the texture flawlessly, but for some textures, the body is slightly above the visible textures, which makes the character look like he's floating if he's standing on that body. But other times, it aligns perfectly with the textures.

Textures that align to body correctly:




Textures that don't align properly:




Here's the code I'm using:


public override void Initialize(World world, SpriteBatch spriteBatch, Texture2D texture, Vector2 position, Texture2D texture2 = null)
            // TODO: Add your initialization code here
            scale = 25;
            this.spriteBatch = spriteBatch;
            this.texture = texture;
            textureOrigin = new Vector2(this.texture.Width / 2, this.texture.Height / 2);
            /*rectangle = new Rectangle(0, 37, 36, 36);
            body = BodyFactory.CreateRectangle(world, ConvertUnits.ToSimUnits(36), ConvertUnits.ToSimUnits(36), 1f);
            body.BodyType = BodyType.Static;
            body.Position = ConvertUnits.ToSimUnits(position);*/
            uint[] data = new uint[this.texture.Width * this.texture.Height];

            Vertices textureVertices = PolygonTools.CreatePolygon(data, this.texture.Width, true);
            Vector2 centroid = -textureVertices.GetCentroid();
            textureVertices.Translate(ref centroid);
            Origin = -centroid;

            textureVertices = SimplifyTools.ReduceByDistance(textureVertices, 4f);

            List list = BayazitDecomposer.ConvexPartition(textureVertices);

            Vector2 vertScale = new Vector2(.04f, .04f);
            foreach (Vertices vertices in list)
                vertices.Scale(ref vertScale);

            body = BodyFactory.CreateCompoundPolygon(world, list, 1f, BodyType.Dynamic);
            body.Position = position;


And in the Draw() Method:


spriteBatch.Draw(texture, body.Position * scale, null, Color.White, 0f, textureOrigin, 1f, SpriteEffects.None, 0f);

Is texture to polygon just not suitable for more complicated textures? Any help is appreciated. Thanks!

Nov 16, 2011 at 2:32 PM
Edited Nov 16, 2011 at 2:33 PM

Hi RylandAlmanza,

I have the same problem at the moment. I am pretty sure that the problem is the getCentroid-method. Do not misunderstand me. This mehtod works properly. In fact your/our texture is asymetric.

That means the centroid of an polygon is not computed with the formula  maxWidth / 2 and  maxHeight / 2.

I wonder if it is possible to compute the polygons center like thus from an Rectangle or Square using the maximum X and Y of the polygon. I did not figure out yet how to solve this problem using the polygons vertices...