0
votes

In Farseer XNA4.0 C# Physics engine based on Box2D

if i use BodyFactory.CreateRectangle(world, w, h, density, new Vector2(x, y)); method to create a body

how can i get the width and height back from the body?

currently im saving the width and height but im wondering if it can be retrieved from a fixture or shape or something. have made some attempts but to no avail. it would save me two floats per entity that im creating.

thanks for any help.

1

1 Answers

2
votes

Ill preface this by saying i've never used Farseer, but looking at the class definitions, it doesn't look like there's a simple way to get what you want. If you look at the BodyFactory.CreateRectangle method, it doesn't store directly the Height or Width values:

    public static Body CreateRectangle(World world, float width, float height, float density, Vector2 position,
                                       object userData)
    {
        if (width <= 0)
            throw new ArgumentOutOfRangeException("width", "Width must be more than 0 meters");

        if (height <= 0)
            throw new ArgumentOutOfRangeException("height", "Height must be more than 0 meters");

        Body newBody = CreateBody(world, position);
        Vertices rectangleVertices = PolygonTools.CreateRectangle(width / 2, height / 2);
        PolygonShape rectangleShape = new PolygonShape(rectangleVertices, density);
        newBody.CreateFixture(rectangleShape, userData);

        return newBody;
    }

Instead, it creates a set of vertices that it assigns to the shape of the body (in this case a rectangle), however, it doesn't appear from a cursory glance that there is a way to get at these vertices.

So long answer short, there isn't a direct method that I can find that will give you the straight float value of the height or width of your rectangle. You might be able to get at the vertices in some way and calculate it back out, but this would require you taking the Body and parsing through its fixture list and figuring out which one is your rectangle.

At the end of the day, if you need to get directly at your Height and Width, I would recommend just creating a custom class and storing the body together with the float values, and using getters/setters. It's likely to be a less expensive operation than looping through every fixture on your objects and trying to determine which is your rectangle and then calculating it back out.