August 22, 2019, 09:07:28 AM

Author Topic: Find corners of box  (Read 265 times)

Offline raven

  • Jr. Member
  • **
  • Posts: 6
Find corners of box
« on: February 26, 2019, 01:03:31 PM »
Hi,

i want to be able to know the coords of the corners of a box whether it is rotated or not.

Can anyone help please?

Code: [Select]
Graphics 640, 480

Type Box
Field x:Int, y:Int
Field w:Int, h:Int
Field angle:Float
Function Create:Box(x, y, w, h, angle)
Local b:Box = New Box
b.x = x
b.y = y
b.w = w
b.h = h
b.angle = angle
Return b
EndFunction
Method Draw()
SetHandle(w / 2, h / 2)
SetRotation(angle)
DrawRect(x, y, w, h)
EndMethod
EndType

Global Boxes:TList = New TList

Local b1:Box = New Box.Create(100, 100, 32, 32, 0)
Boxes.AddLast(b1)

Local b2:Box = New Box.Create(510, 320, 48, 48, 32)
Boxes.AddLast(b2)

Local b3:Box = New Box.Create(230, 380, 64, 64, 45)
Boxes.AddLast(b3)

SetClsColor(0, 0, 120)

Repeat
Cls
For Local b:Box = EachIn Boxes
b.Draw()
Next
Flip
Until KeyHit(KEY_ESCAPE) Or AppTerminate()

Offline Derron

  • Hero Member
  • *****
  • Posts: 2334
Re: Find corners of box
« Reply #1 on: February 26, 2019, 06:37:30 PM »
Reply from smartphone. So excuse the shortness of this teply.

As your handle is in the center you can easily calculate the new corner points A B C D of the rectangle by utilizing sin/cos aka trigonometry. Centered handle, midpoint between sides and a corner create a 90° triangle allowing to use sin/cos to calculate missing sides...and so new endpoints.

Then use an approach like this:
https://stackoverflow.com/questions/17136084/checking-if-a-point-is-inside-a-rotated-rectangle

Which means: sum up areas of all triangles the mouse coord can create with two corner points of the rotated rectangle. Is that sum bigger than the area of the rectangle then the cursor is outside.


Another approach is to use the rotation matrix to retrieve that information.
My approach above is easier to understand and only requires knowledge of 7/8th grade school mathematics ...you just need to remember.


Bye
Ron

Offline Matty

  • Hero Member
  • *****
  • Posts: 715
    • MattiesGames
Re: Find corners of box
« Reply #2 on: February 27, 2019, 05:53:18 AM »
deleted