Reputation: 23
Say I have a square with a rotation of 90 degrees (I have found this to be Up for my computer) and a second square with a rotation of 75 degrees. The top left corner of the first square and the bottom left corner of the second, are connected.
[]
My goal is to use trigonometry to edit the position of the second square so that its bottom right corner and the first squares top right corner (the two highlighted corners) connect.
On a piece of paper that's not too hard. I'd use sin and cos to find x and y offsets. In this case, the code would look similar to:
let xOffset = 15 - (cos(15) * 15)
let yOffset = sin(15) * 15
secondSquare.position = point(secondSquare.position.x + xOffset, secondSquare.position.y - yOffset)
I'd like to clarify that the reason I multiplied the sin and cos of 15 degrees, by 15, is because the width of both squares is 15.
Now this math was done by drawing a right triangle perpendicular to the x axis. But how would I solve the same problem if the first square wasn't at a perfect 90 degree rotation and parallel to the x axis?
[]
My overall question is, I did all this math using the x axis as a basis. But what does Swift use to find sin, cos, and tan? And how can I use it to solve all variations of this same problem?
Upvotes: 0
Views: 519
Reputation: 535306
The way to do what you're doing, in code, with rectangular views or with drawings of rectangles, is to apply a transform. It is easy to rotate a view or rectangle by given angle.
Upvotes: 0