gpt4 book ai didi

c++ - 一条线相对于另一条线的角度

转载 作者:太空宇宙 更新时间:2023-11-04 14:01:59 24 4
gpt4 key购买 nike

enter image description here虽然这是一个简单的问题,但我可能以错误的方式思考,因此找不到正确的方法。

假设我有一条线,比如第 1 行,从 m_StartPoint1 开始到 m_EndPoint1 结束。我想画另一条线,比如线 2,从 m_EndPoint1 开始,与线 1 的 alpha 角度恒定。基本上我的目标是画一个箭头。

我正在使用以下代码来计算第 2 行的 x、y 坐标。

 const float ARROW_ANGLE=-PI/8.0;
wxPoint p;
p.x=m_EndPoint.x+ARROW_LENGTH*sin(ARROW_ANGLE);
p.y=m_EndPoint.y+ARROW_LENGTH*cos(ARROW_ANGLE);
m_ArrowHead1=new CLine(m_EndPoint,p,color,PenWidth); //Draws a line from m_EndPoint to p

当直线 1 的角度小于 90(以度为单位)时,此计算效果很好。但是,当线 1 的角度发生变化时,箭头显示不正确。基本上,用户应该能够按照他/她的意愿绘制线 1,并且无论线 1 的角度如何,箭头线都应该正确显示。

我已经将第 1 行表示为 vector ,并通过以下代码获得了它的角度:

class CVector2D
{
wxPoint m_StartPoint, m_EndPoint;
public:
CVector2D():m_StartPoint(),m_EndPoint() {}
CVector2D(wxPoint p1, wxPoint p2):m_StartPoint(p1),m_EndPoint(p2) {}

float GetSlope(void)
{
return float(m_EndPoint.y-m_StartPoint.y)/float(m_EndPoint.x-m_StartPoint.x);
}

float GetSlopeAngleInRadians()
{
/*Will return the angle of the vector in radians
* The angle is the counterclockwise rotation therefore it is negative
*/
float slope=GetSlope();
float InRadians=atan2(float(m_EndPoint.y-m_StartPoint.y),float(m_EndPoint.x-m_StartPoint.x));
if(InRadians<=0) return InRadians;
return -(2*PI-InRadians);
}
};

然后我尝试用下面的代码计算:

CVector2D vector(m_StartPoint,m_EndPoint);
float vector_angle=vector.GetSlopeAngleInRadians();
float total_angle=vector_angle+ARROW_ANGLE;
wxPoint p;
p.x=m_EndPoint.x+ARROW_LENGTH*cos(total_angle);
p.y=m_EndPoint.y+ARROW_LENGTH*sin(total_angle);
m_ArrowHead1=new CLine(m_EndPoint,p,color,PenWidth);

但是,这段代码也不起作用。任何想法将不胜感激。

最佳答案

这里的困难可能更多是关于数学而不是编程。但是,您需要小心处理奇点。

如何防止在 90 度处被零除:

float GetSlope(void)
{
return float(m_EndPoint.y-m_StartPoint.y)/float(m_EndPoint.x-m_StartPoint.x);
}

我推荐基于点积的数学,请参阅: How to find out if the angle between two vectors is external or internal?

附言为什么不用 double 而不是 float?

关于c++ - 一条线相对于另一条线的角度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18942907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com