c# - 从点数组中查找给定点坐标的索引
问题描述
给定一个 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,因此生成的椭圆会消失它从身体进一步得到)我花了几天时间试图找出我在这里做错了什么,并尝试了十几种不同的方法试图找出我的数学错误在哪里,但我没有看到它。
解决方案
我假设 _points 应该是一个 PointD 数组;这是获得离数组最近的点的最短方法(calcdistance 应该是一个计算欧几里德距离的简单函数):
PointD p = _points.OrderBy(p => CalcDistance(p, gievnPoint)).First();
推荐阅读
- google-colaboratory - 从 Google Colabortory 下载输出文件
- php - axios 请求返回错误 500 (laravel, axios & vuejs)
- python - 为什么这个方法说 1 的平方是 3?
- c - 为什么未签名被视为已签名?
- google-cloud-pubsub - 如何推送到 GCP 发布/订阅中的多个端点?
- javascript - Pascal Case(或 Upper Camel Case),但允许使用 HTMLInputElement 之类的名称?
- python - 使用 Python 访问 Youtube 数据 API 时出错
- r - 如何在零膨胀负二项式模型中预测具有偏移量的新数据
- c - cgo 与使用线程本地存储的 C 库交互
- python - 使用 Python Websockets 库的多线程服务器