ofxBox2d - coordinates of the corners of the rectangle

I’m start working with OF and box2d library, and I have a problem. I have ofxBox2dRect rectangle and how can I get coordinates of the each corners of this rectangle of each frame. I need this is because I have a ofImage image and I would like to move this image like a rectangle subjected physics.

1 Like

Assuing that your vector of pointers that contains the ofxBox2dRect objects is called “rects”

float centerX = rects[i].get()->getPosition().x;
float centerY=rects[i].get()->getPosition().y;

This will give you the center of each box2d object. You can then get the width:

float w = rects[i].get()->getPosition().x;

and finally do:

float startX = centerX - w/2;

which will give you the top left corner of the rectangle.

Hope it helps. I often struggle with box2d as well. I find the documentation scarce and even the existing one is not very good. I find it easier to just look at the .h files of each object and see what is available so that I know how to calculate what I want.

Good luck.

Thanks for help, but this working when ofxBox2dRect rects is straight, but when rects is rotated or tilted, for example, when the ball hit him and physics moved him its not working.

I had written something some time ago:

for(unsigned int i=0; i<circles.size(); i++)
    float pX=circles[i].get()->getPosition().x;
    float pY=circles[i].get()->getPosition().y;
    float a=circles[i].get()->getRotation();
    float rad = circles[i].get()->getRadius();
    ofTranslate(pX, pY);

The above is for a circle, but using my first answer you can apply it to rectangles too. Take note that the getPosition() function returns the center of the object (circle or rectangle) so you need to set anchor point of the image to the center.

Let me know if it helped.