find the angle of point related to pivot
It’s been days that I’m working on a project which I have to use convex hull in it, and specific method of graham scan. The problem has been solved till the place I want to sort the points. So the story is that I have collected bunch of points which they are from the type Point and their coordinates are relatives. Mean they come from the mouse event x and y. So I have collected the mouse positions as x and y of the points. And I want to find the an开发者_运维知识库gle related to the pivot point. Does anyone have a piece of code to calculate that angle? Many and many thanks, the image below is what I need:
Use
Math.atan2(dy, dx)
where dy
and dx
represent the vertical and horizontal difference between the point and pivot point.
A few notes to keep in mind:
The reference (0 radians) is by convention pointing to the right, not to the left as in your image. If you really want to measure it from the left, you'd have to do
Math.PI - angle
to convert it.The
Math
-trigonometry functions work in radians. To convert the results to degrees, you can useMath.toDegrees
.In the mathematical world, increasing y-values point upwards. In your image, their pointing downwards.
I would use the dual-definition of the dot product to calculate this, as you skip over the nasty point of what happens at vertical lines, and dealing with quadrants
(Forgive my notation as math doesn't work too well in markdown...)
Where A
and B
are both 2D vectors with x
and y
components, and theta
is the angle between them:
dot(A, B) = ax * bx + ay * by
and
dot(A, B) = |A| * |B| * cos(theta)
...where |A|
is the length of A
, which can be computed with Pythagorean theorem:
|A| = sqrt(ax^2 + ay^2)
Therefore:
theta = acos((ax * bx + ay * by) / (|A| * |B|))
to get the angle from the horizontal of the line linking any two points p1 & p2: Angle = atan((p1.y - p2.y) / (p1.x - p2.x)
So, your black angle = atan((454-243) / (286-108)) NOTE: y sign reversed as your y axis starts at top-left rather than bottom-left
Angle will be in radians, to convert to degrees muliply by (180/pi)
精彩评论