# How to detect touch area of rotated rectangle?

Hi, I would like to know how to detect touch area of rotated rectangle?

My idea so far is to detect inside boundaries of 4 lines.

But I wonder if there is any simpler solution than this.

Any suggestions?

Hi cuinjune,

you need an oriented bounding box (obb) test. Rotate your obb with your testing point back to an axis aligned bounding box (aabb) with your obb rotation angle, then check the point against outside of the aabb.

Regards

Michael

Thank you!

Hi,
I dont know if you already solved this but you can also use a polygon with a rectangle shape and then create a functions to check if the coordinates of the touch event are inside that shape.
Here is a code i took from an old project where i used this approach. When i was working on this i found this solution on stackoverflow and worked great.

``````bool testApp::isInside(){
ofPoint p = ofPoint(mouseX,mouseY);
int counter = 0;
int i;
double xinters;
ofPoint p1,p2;
int N = shapePoints.size();
float margin = 0;
p1 = shapePoints;
for (i=1;i<=N;i++) {
p2 = shapePoints[i % N];
if (p.y > MIN(p1.y,p2.y) + margin) {
if (p.y <= MAX(p1.y,p2.y)) {
if (p.x <= MAX(p1.x,p2.x)) {
if (p1.y != p2.y) {
xinters = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
if (p1.x == p2.x || p.x <= xinters )
counter++;
}
}
}
}
p1 = p2;
}

if (counter % 2 == 0)
return false;
else
return true;

}``````

Hi,
Something good to know (in my opinion) :

Suppose you have this rectangle:

``````ofRectangle rect( 350, 100, 400, 300 );
``````

And that you draw it like that:

``````ofTranslate( dx, dy, 0 );
ofRotate( angle, 0, 0, 1 );
ofScale( scaleX, scaleY, 1 );
ofRect( rect );
``````

You can get the same result with:

``````ofMatrix4x4 matrix;
matrix.glTranslate( dx, dy, 0 );
matrix.glRotate( angle, 0, 0, 1 );
matrix.glScale( scaleX, scaleY, 1 );
ofMultMatrix(matrix);
ofRect( rect );
``````

OK, but what’s the point ?
The point is that you can test if a point (x,y) is in the drawned rectangle using the inverse matrix:

``````ofVec3f mouse( x, y, 0 );
mouse = mouse * matrix.getInverse();
bool isInside = rect.inside( mouse );
``````

You can use this method in your case and more generaly if you want to apply more complex transformations to the rectangle.
Here’s an example:
src.zip (1.4 KB)

3 Likes