从Points数组中查找给定Point坐标的索引

时间:2018-06-03 06:33:37

标签: c# math trigonometry ellipse

给定一个Point数组和一个任意的x,y坐标,找到最接近给定坐标的_points的索引

PointD[] _points
//create a list of x,y coordinates:
for (int i = 0; i < _numberOfArcSegments + 1; i++)
{

    double x1 = _orbitEllipseSemiMaj * Math.Sin(angle) - _focalDistance; //we add the focal distance so the focal point is "center"
    double y1 = _orbitEllipseSemiMinor * Math.Cos(angle);

    //rotates the points to allow for the LongditudeOfPeriapsis. 
    double x2 = (x1 * Math.Cos(_orbitAngleRadians)) - (y1 * Math.Sin(_orbitAngleRadians));
    double y2 = (x1 * Math.Sin(_orbitAngleRadians)) + (y1 * Math.Cos(_orbitAngleRadians));
    angle += _segmentArcSweepRadians;
    _points[i] = new PointD() { x = x2, y = y2 };
}
我正在绘制一个代表轨道的椭圆。我首先创建上面的点阵,然后当我绘制它时,我(尝试)找到最接近轨道体的位置的点。

要做到这一点,我一直在尝试计算从椭圆中心到身体的角度:

public void Update()
{    
    //adjust so moons get the right positions (body position - focal point position) 
    Vector4 pos = _bodyPositionDB.AbsolutePosition - _positionDB.AbsolutePosition;   
    //adjust for focal point
    pos.X += _focalDistance; 

    //rotate to the LonditudeOfPeriapsis. 
    double x2 = (pos.X * Math.Cos(-_orbitAngleRadians)) - (pos.Y * Math.Sin(-_orbitAngleRadians));
    double y2 = (pos.X * Math.Sin(-_orbitAngleRadians)) + (pos.Y * Math.Cos(-_orbitAngleRadians));

    _ellipseStartArcAngleRadians = (float)(Math.Atan2(y2, x2));  //Atan2 returns a value between -180 and 180; 
}

然后:

double unAdjustedIndex = (_ellipseStartArcAngleRadians / _segmentArcSweepRadians);
while (unAdjustedIndex < 0)
{
    unAdjustedIndex += (2 * Math.PI);
}
int index = (int)unAdjustedIndex;

椭圆绘制正常,(点阵数正确,一旦调整了视屏和相机偏移和缩放,一切都很好) 但是不是从正确的点开始(我正在减少颜色中的alpha值,因此得到的椭圆随着它从身体越远而逐渐消失) 我花了好几天试图找出我在这里做错了什么,并尝试了十几种不同的东西,试图找出我的数学错误,但我没有看到它。

1 个答案:

答案 0 :(得分:2)

我假设_points应该是PointD的数组; 这是获得最接近数组的最短路径(calcdistance应该是一个计算欧氏距离的简单函数):

PointD p = _points.OrderBy(p => CalcDistance(p, gievnPoint)).First();