我正在尝试将图像移向我的鼠标指针。基本上,我得到点之间的角度,沿x轴移动角度的余弦,沿y轴移动角度的正弦。
但是,我没有很好的计算角度的方法。我得到x的差异和y的差异,并使用Δy/Δx的arctangent。象限1中的最终角度是正确的,但其他3个象限是错误的。象限2的范围从-1到-90度。象限3总是等于象限1,象限4总是等于象限4. 是否有一个方程可以用来找到1-360度之间的2个点之间的角度?
注意:我不能使用atan2(),我不知道矢量是什么。提前谢谢。
答案 0 :(得分:1)
// This working code is for Windows HDC mouse coordinates gives the angle back that is used in Windows. It assumes point 1 is your origin point
// Tested and working on Visual Studio 2017 using two mouse coordinates in HDC.
//
// Code to call our function.
float angler = get_angle_2points(Point1X, Point1Y, Point2X, Point2Y);
// Takes two window coordinates (points), turns them into vectors using the origin and calculates the angle around the x-axis between them.
// This function can be used for any HDC window. I.e., two mouse points.
float get_angle_2points(int p1x, int p1y, int p2x,int p2y)
{
// Make point1 the origin, and make point2 relative to the origin so we do point1 - point1, and point2-point1,
// Since we don’t need point1 for the equation to work, the equation works correctly with the origin 0,0.
int deltaY = p2y - p1y;
int deltaX = p2x - p1x; // Vector 2 is now relative to origin, the angle is the same, we have just transformed it to use the origin.
float angleInDegrees = atan2(deltaY, deltaX) * 180 / 3.141;
angleInDegrees *= -1; // Y axis is inverted in computer windows, Y goes down, so invert the angle.
//Angle returned as:
// 90
// 135 45
//
// 180 Origin 0
//
//
// -135 -45
//
// -90
// The returned angle can now be used in the C++ window function used in text angle alignment. I.e., plf->lfEscapement = angle*10;
return angleInDegrees;
}
答案 1 :(得分:0)
如果您无法直接使用atan2(),您可以自行实施内部计算:
atan2(y,x) = atan(y/x) if x>0
atan(y/x) + π if x<0 and y>0
atan(y/x) - π if x<0 and y<0
答案 2 :(得分:0)
答案 3 :(得分:0)
这是我使用的代码,它看起来工作得很好。
atan(x/y)+(180*(y<0))
其中X是点Xs(x2-x1)之间的差,Y是点Ys(y2-y1)之间的差。
atan((x2-x1)/(y1-y2))+(180*((y1-y2)<0))
我希望这对您有用,并且您希望得到一个已有一年半的问题的答案。