# Find the 4 Corners of a Bounding Box of a Rotated, Offsetted Square

How does one find the coordinates of the 4 corners of a bounding box of a square of width w and height h that is rotated theta degrees and is offset from the origin x in the x direction and y in the y direction?

Here is a visual example of what I mean: Here is some python3 code that I came up with, but it only works in the right quadrants except when theta = 0 or 360 or etc.:

import math

def bounds(x,y,w,h,theta):
theta = theta * math.pi / 180

A = ( x, y+round((math.sin(theta)*w), 2) )
B = ( x+round((w/math.sin(theta)), 2), y+round((math.sin(theta)*w), 2) )
C = ( x+round((w/math.sin(theta)), 2), y+round((math.cos(theta)*h), 2) )
D = ( x, y+round((math.cos(theta)*h), 2) )
print(A)
print(B)
print(C)
print(D)


I was reading this but I could not figure it out for my specific problem.

Any help is much appreciated. Next time I will use matrices to store all the transformation data because this would be so much easier that way.

• i recommend you the book Christer Ericson Real-Time Collision Detection thank me latter. Bye bye May 21 '17 at 17:33
• @Haruko Thanks for this. This should be especially helpful when building a 3D environment that involves any sort of collision. May 21 '17 at 18:38

Figured it out. The main part is finding out how to get the corners of the square. I suggest brute forcing through the trigonometry on paper to figure out how to get the 4 corners of the square. After that, it's just a matter of finding the width between the furthest corners in the x direction and finding the height between the furthest corners in the y direction, and finally adding them up with the top-left x,y coordinates of the bounding box, appropriately for each corner of the bounding box.

Here is a pseudo code:

// corner functions (tricky part)
get_top_left_corner = function() {
return [my_x, my_y]
}

get_top_right_corner = function() {
return [my_x + cos(angle) * my_w,
my_y - sin(angle) * my_w]
}

get_bottom_left_corner = function() {
return [my_x + sin(angle) * my_h,
my_y + cos(angle) * my_h]
}

get_bottom_right_corner = function() {
return [(my_x + cos(angle) * my_w)  +  (sin(angle) * my_h),
(my_y - sin(angle) * my_w)  +  (cos(angle) * my_h)]
}

// [x,y] coordinates of corners of rotated square
tl = get_top_left_corner()
tr = get_top_right_corner()
bl = get_bottom_left_corner()
br = get_bottom_right_corner()

// coordinates of bounding box's top left corner
ax = min( tl.x, tr.x, bl.x, br.x )
ay = min( tl.y, tr.y, bl.y, br.y )

// width & height of bounding box
w = max( tl.x, tr.x, bl.x, br.x ) - ax
h = max( tl.y, tr.y, bl.y, br.y ) - ay

// [x,y] coordinates of bounding box's corners
A = [ax, ay]
B = [ax + w, ay]
C = [ax + w, ay + h]
D = [ax, ay + h]