Im trying to create a body of a irregular 2D sprite Farseer 3.3.1. Could it be done with using BodyFactory.CreateCompoundPolygon method?
Asked
Active
Viewed 1,205 times
1 Answers
2
this is a method from one of my projects. Its a little specific to my architecture but should be usable for yourself.
One thing to consider is the scaling. You would be best to replace this with the ConvertUnits.ToSimUnits etc which I am sure you are familiar with.
public static Body CreateBodyFromImage(Game game, World world, string textureName)
{
//Load the passed texture.
Texture2D polygonTexture = game.Content.Load<Texture2D>(textureName);
//Use an array to hold the textures data.
uint[] data = new uint[polygonTexture.Width * polygonTexture.Height];
//Transfer the texture data into the array.
polygonTexture.GetData(data);
//Find the verticals that make up the outline of the passed texture shape.
Vertices vertices = PolygonTools.CreatePolygon(data, polygonTexture.Width);
//For now we need to scale the vertices (result is in pixels, we use meters)
Vector2 scale = new Vector2(0.07f, 0.07f);
vertices.Scale(ref scale);
//Partition the concave polygon into a convex one.
var decomposedVertices = BayazitDecomposer.ConvexPartition(vertices);
//Create a single body, that has multiple fixtures to the polygon shapes.
return BodyFactory.CreateCompoundPolygon(world, decomposedVertices, 1f);
}

Nick
- 948
- 2
- 12
- 24
-
There is also a problem of setting the Centroid of the body. I followed the code provided in the Farseer 3.3.1 Sample //Vector2 centroid = -textureVertices.GetCentroid(); //textureVertices.Translate(ref centroid); //basketOrigin = -centroid; This makes the object still with now movements at all – Yousuf Tafhim Aug 26 '11 at 11:03
-
Thank @Nick I can get to see the sprite on the screen at least. But the collision still doesnt take place and there issue with applying force occurs if (kstate.IsKeyDown(Keys.Down)) _compound.ApplyForce(ConvertUnits.ToSimUnits(Vector2.UnitY)); if (kstate.IsKeyDown(Keys.Up)) _compound.ApplyForce(ConvertUnits.ToSimUnits (-Vector2.UnitY)); This should translate the object but it doesn't rather it rotates the object. Any idea why is it doing that so? – Yousuf Tafhim Aug 26 '11 at 11:08
-
@Yousuf, Are you running DebugViewXNA? it would be wise to be 100% that your body is in the same position as your sprite and that it is the correct scale. Am I right in assuming that _compound is the body created using the method? – Nick Aug 26 '11 at 12:50
-
@Yousuf, I would really check the DebugView then and make sure things are where you think they are. Also make sure you are setting up your body afterwards, eg setting IsEnabled to true, BodyType to dynamic etc. – Nick Aug 26 '11 at 14:47