C# 从点数组中查找给定点坐标的索引

C# 从点数组中查找给定点坐标的索引,c#,math,trigonometry,ellipse,C#,Math,Trigonometry,Ellipse,给定一个点阵列和任意x,y坐标,找到最接近给定坐标的点的索引 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 f

给定一个点阵列和任意x,y坐标,找到最接近给定坐标的点的索引

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 };
}
然后:

double unAdjustedIndex=(_EllipseStatarAngleradians/_segmentArcSweepRadians);
而(未调整的指数<0)
{
未调整的指数+=(2*Math.PI);
}
int索引=(int)未调整的索引;
椭圆绘制得很好,(点阵列是正确的,并且在调整了viewscreen、摄影机偏移和缩放后一切都很好) 但是没有从正确的点开始(我正在减少颜色中的alpha值,这样得到的椭圆会随着距离身体越远而逐渐消失)
我花了几天的时间试图找出我做错了什么,尝试了十几种不同的方法试图找出我的数学错在哪里,但我没有看到

我假设_点应该是点d的数组; 这是获得阵列最近点的最短方法(calcdistance应该是计算欧几里德距离的简单函数):


哎呀,是的,我的坏消息应该是D[]\u点;仅剪切代码的重要位时出错。在~80到255大小的点阵列上排序与Math.Sin、Cos、Atan之间的成本差异是什么?关于索引,您可以将其转换为常规for循环并保存最小索引。关于性能问题,您应该对其进行测量。在我看来,排序成本比数学函数要低。虽然我更愿意找出代码的错误,但这是一种更简单的方法。这个问题没有得到更多的回答,所以我将给出一个公认的答案。你认为离给定点最近的椭圆上的点与椭圆中心到给定点的角度相同的假设是不正确的。要使此假设正确,需要首先平移椭圆和点,使椭圆的中心为0,0。然后需要缩放elipse(及其点),以便elipse变成一个圆。然后你可以使用你的角度假设。你没有错,这正是Update()函数所做的,虽然不是对椭圆,而是对我们找到角度的点。它没有调整偏心率,因为在这种情况下不需要。轨道物体所在的点将穿过椭圆的每个点。
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;
PointD p = _points.OrderBy(p => CalcDistance(p, gievnPoint)).First();