Search code examples
c#.netxna-4.0farseer

PolygonShape is not updated by its body


I'm trying to define a polygon to be updated by a body bounded by a physical world. Here it goes my attempt:

public Body _body;
public Shape _shape;
_primitiveBatch = new PrimitiveBatch(_game.GraphicsDevice);
_shape = new PolygonShape(_vertices, 1);
Vector2 _position = FarseerPolygon.getCenter(((PolygonShape)_shape).Vertices);
_body = new Body(_world);
_body.Position = _position;
_body.CreateFixture(_shape);
_body.BodyType = BodyType.Dynamic;
_body.Restitution = 0.9f;
_body.Friction = 1f;

The body changes its position but not the shape. Body.CreatePolygon also doesn't work. Any help would really be appreciated because I'm stucked in here... Thank you,


Solution

  • The polygon is not supposed to change position. It's a performance thing. The Fixture and its Shape are designed to exist in "Model Space" (close to (0,0)) and not change. Then the Body defines the transform to place that shape in "World Space".

    To get the individual points of a polygon in world space, given a Fixture fixture, do this:

    var shape = fixture.Shape as PolygonShape;
    Transform transform;
    fixture.Body.GetTransform(out transform);
    
    foreach(Vector2 vertex in shape.Vertices)
    {
        Vector2 theTransformedVertex = MathUtils.Multiply(ref transform, vertex);
    }
    

    You need these usings from Farseer, for the above code to work:

    using FarseerPhysics.Collision.Shapes;
    using FarseerPhysics.Common;
    

    (This code written against Farseer 3.3.1)