Reputation: 19733
I have the following parameters
How do I check whether the point lies within the rectangle?
Any pointers will be greatly appreciated. Thanks.
Upvotes: 1
Views: 2803
Reputation: 13841
Basic check
If your rectangle is not rotated the problem is limited to check if Point (x,y) is between some range
(rectangle.x, rectangle.x + rectangle.width)
(rectangle.y, rectangle.y + rectangle.height)
Adding rotation
As the rectangle is rotated you could make the inverse rotation to bring the point to the "unrotated state" and make the previous check.
How to "un-rotate" the point
Well. If your rectangle is rotated 27º, the "unrotation" will have to be -27º (from the same center of rotation point).
How to rotate a point given a center of rotation point?
Well, you must:
Rotation on origin
You have to make matrix multiplication Ax. Where A is the matrix and x is the (x, y) vector of the point to rotate.
Matrix A is built this way
Upvotes: 5
Reputation: 30147
Convert all coordinates into rotated reference frame, in which rectangle is in the center and aligned along axis. Then just check coordinate ranges.
To convert between frames use these formulas: http://en.wikipedia.org/wiki/Rotating_reference_frame#Relation_between_positions_in_the_two_frames
P.S. Sorry, this link fits more to the static case: http://en.wikipedia.org/wiki/Rotation_(mathematics)#Matrix_algebra
Upvotes: 0
Reputation: 3849
If you are OK with using awt, you can create a Shape instance then use: Shape.contains(Point2D p).
Docs are here: http://docs.oracle.com/javase/1.5.0/docs/api/index.html?java/awt/Graphics.html Tutorial for Java 2D is here: http://java.sun.com/developer/technicalArticles/GUI/java2d/java2dpart1.html#1
HTH
Upvotes: 0