从3个点检索正角度或负角度

问题描述 投票:5回答:4

我在2D空间的中心点周围旋转点。这些点是中心点,旧鼠标位置和新鼠标位置。我的旋转功能工作正常,我可以完美地计算角度。但是如果用户将鼠标移动到应该被解释为逆时针的方向,我想计算负角度。

例如,如果您高于(小于)中心点的y值,则向右移动鼠标(正x轴)应该顺时针旋转,但如果实际低于(大于),它应逆时针旋转中心点的y值。

这就是我所拥有的:

PointF centerPoint;
PointF oldPoint;
PointF newPoint;

double Xc = centerPoint.X;
double Yc = centerPoint.Y;
double Xb = oldPoint.X;
double Yb = oldPoint.Y;
double Xa = newPoint.X;
double Ya = newPoint.Y;

double c2 = (Math.Pow(Xb - Xa, 2) + Math.Pow(Yb - Ya, 2));
double a2 = (Math.Pow(Xb - Xc, 2) + Math.Pow(Yb - Yc, 2));
double b2 = (Math.Pow(Xa - Xc, 2) + Math.Pow(Ya - Yc, 2));

double a = Math.Sqrt(a2);
double b = Math.Sqrt(b2);

double val = (a2 + b2 - c2) / (2 * a * b);
double angle = Math.Acos(val);

因此我需要一种方法在需要时使角度为负,因此点顺时针或逆时针旋转以跟随鼠标位置。

c# math rotation point angle
4个回答
7
投票

试试这个,但我不确定:

double v1x = Xb - Xc;
double v1y = Yb - Yc;
double v2x = Xa - Xc;
double v2y = Ya - Yc;

double angle = Math.Atan2(v1x, v1y) - Math.Atan2(v2x, v2y);

3
投票
private double AngleFrom3PointsInDegrees(double x1, double y1, double x2, double y2, double x3, double y3)
{
    double a = x2 - x1;
    double b = y2 - y1;
    double c = x3 - x2;
    double d = y3 - y2;

    double atanA = Math.Atan2(a, b);
    double atanB = Math.Atan2(c, d);

    return (atanA - atanB) * (-180 / Math.PI); 
    // if Second line is counterclockwise from 1st line angle is 
    // positive, else negative
}

0
投票

看起来你需要做的就是

angle = angle > Math.PI ? angle - 2*Math.PI : angle;

在代码的最后。这将使您在由centerPoint和oldPoint定义的直线右侧顺时针旋转,在左侧逆时针旋转,无论方向如何。


0
投票

给定向量(x1,y1)和(x2,y2),我建议计算叉积和点积,然后在它们上使用Atan2()。这将适用于两个向量都非零并且向量长度“合理”的所有情况。

© www.soinside.com 2019 - 2024. All rights reserved.