c# - C#在半径内的网格上获取附近的点
问题描述
我有一个具有 X 和 Y 坐标的网格。在这个网格上,我有一个起点,我想获得一定半径内的所有附近单元格。
我制作了以下函数,该函数在每个方向上 +1 并返回点。
public List<Point> GetLocationsStraightLine(Point fromLocation, int Distance)
{
var nearbySpots = new List<Point>();
int StartDistance = 1;
while (StartDistance < Distance)
{
nearbySpots.Add(new Point(fromLocation.X, (short)(fromLocation.Y - StartDistance)));
nearbySpots.Add(new Point((short)(fromLocation.X + StartDistance), fromLocation.Y));
nearbySpots.Add(new Point(fromLocation.X, (short)(fromLocation.Y + StartDistance)));
nearbySpots.Add(new Point((short)(fromLocation.X - StartDistance), fromLocation.Y));
StartDistance++;
}
return nearbySpots;
}
这将从我的起点返回直线上的所有点。但是我也想抓住中间点。
这是我目前得到的(对不起,糟糕的形象)
但是,我希望能够输入 2 的距离并在起始位置周围获得完整的正方形。
所以我问有没有什么简单的方法可以让我得到对角线,而不仅仅是从起点开始的直线?
解决方案
由于它是一个矩形,因此您可以使用一种非常简单的方法。假设这Distance
总是积极的:
public List<Point> GetLocationsStraightLine(Point fromLocation, int Distance) {
var nearbySpots = new List<Point>();
for (int i = -Distance; i <= Distance; ++i)
for (int j = -Distance; j <= Distance; ++j)
nearbySpots.Add(new Point(fromLocation.X + j, fromLocation.Y + i));
return nearbySpots;
}
这个想法是从左上角开始,逐行添加矩形中的每个点,到右下角结束。
推荐阅读
- printing - 如何打印我指示的点之间的距离?
- python - 如何在创建对象时增加父类中的静态计数器
- excel - 如果它们包含关键字,如何将行从一个工作表移动到另一个工作表
- node.js - 将 OKTA 集成到现有的 AD 应用程序中 - NodeJS ExpressOIDC
- c - C 中的队列和动态分配结构的问题
- javascript - 如何根据.cshtml中的不同下拉值显示不同的表格?
- php - 在 woocommerce 中执行自定义订单操作后出现“白屏”
- three.js - Raycast 在鼠标点击时未检测到导入的 fbx
- jenkins - 由于 .svn 文件夹,Jenkins 作业因“mlDeployApp”任务而失败
- python - 有没有一种更有效的方法来查找列表的最小值/最大值/总和,而无需创建另一个变量来查找总和