Ragunath Jawahar
Ragunath Jawahar

Reputation: 19733

Collision detection in a rotated rectangle

I have the following parameters

  1. x,y co-ordinates (top-left only) of a rotated rectangle
  2. Angle of rotation
  3. The rectangle is rotated through the center
  4. Width and Height of the rectangle
  5. Co-ordinates of the point whose presence within the rectangle has to be checked

How do I check whether the point lies within the rectangle?

Any pointers will be greatly appreciated. Thanks.

Upvotes: 1

Views: 2803

Answers (3)

helios
helios

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:

  1. translate the thing to make (0,0) the center point: it is, translate the original point (-x, -y) where (x, y) is the point of rotation
  2. apply rotation on origin (see section below)
  3. undo the first transformation (translate (x, y) where (x, y) is the point of rotation

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

Suzan Cioc
Suzan Cioc

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

davidfrancis
davidfrancis

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

Related Questions