[英]How can I make something move in a specific order in a matrix?
所以我遇到了这个问题:我想从一个黑点移动到另一个像这样的地方:
但是每当我尝试执行此操作时,它就会像这样移动:
您只能一次向北,向南,向东和向西移动。 我试图做这样的事情:
int distance = game.Distance(myPirate.Loc,loc);
List<Direction> allDirections = new List<Direction>() { Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST, Direction.NOTHING };
Location destination;
foreach (Direction dir in allDirections)
{
destination = game.Destination(myPirate, dir);
int distance2 = game.Distance(destination, loc);
if (distance2 < distance) return dir;
}
return Direction.NOTHING;
但是,每当我尝试这段代码时,我都会得到以下结果:
谁能帮助我找出如何像第一张图片而不是第二张图片那样运动? 您将获得矩阵中两个黑色正方形的位置。 如果您还有其他需要,请告诉我。
正如@ap和@AlexeiLevenkov在其注释中已经提到的那样,您可以使用任何线条绘制算法来解决您的任务。
将矩阵视为一个像素字段(屏幕)。 您想以最短的方式从起点移动到终点,这当然是一条直线(我相信您可以从几何路线中记住这一点)。 因此,您必须在栅格像素字段上的两个点之间“绘制”一条直线。 那正是那些线描算法的重点。
让我们使用简单的DDA。
首先,必须确定路径线的斜率:
double slope = (endPoint.Y - startPoint.Y) / (double)(endPoint.X - startPoint.X);
然后,您应该查看斜率绝对值是小于还是大于1。这是根据算法确定的。 如果它小于或等于1,那么我们将在每一步上沿水平方向移动(因此我们以dX = 1进行 “采样”)。 在另一种情况下,我们将沿垂直方向移动(“采样”为dY = 1 )。
我们必须准备“线”:我们根据斜率计算dX和dY偏移量。 对于dX == 1的情况,我们将在每次移动中向左或向右移动,另外,使用dY值计算下一个垂直“跳跃”。 如果我们确定应该向上或向下移动,则通常会另外执行此操作。 但是由于每次迭代只允许移动一次,所以我们将需要跳过水平移动而改为垂直移动。
在下一个示例代码中,我将省略dY == 1的情况。 您一定可以自己编写。 此外,这段代码并不是那么整洁,但是为了简单起见,我就这样保留它。 您可以对其进行优化和重构。
private double dX, dY;
private double currentX, currentY;
void PrepareMoving(Point startPoint, Point endPoint)
{
double slope = (endPoint.Y - startPoint.Y) / (double)(endPoint.X - startPoint.X);
if (Math.Abs(slope) <= 1.0)
{
this.dX = Math.Sign(endPoint.X - startPoint.X);
this.dY = slope;
}
else
{
this.dY = Math.Sign(endPoint.Y - startPoint.Y);
this.dX = slope;
}
this.currentX = startPoint.X;
this.currentY = startPoint.Y;
}
Direction DoNextMove(Point target)
{
// If we already have reached the destination...
if (new Point((int)this.currentX, (int)this.currentY) == target)
{
return Direction.NOTHING;
}
// if the horizontal moving is "primary"
if (Math.Abs(this.dX) == 1.0)
{
double nextValue = this.currentY + this.dY;
try
{
// we have to move up or down if we've got a "jump"
if (Math.Round(nextValue) != Math.Round(this.currentY))
{
return this.dY > 0 ? Direction.SOUTH : Direction.NORTH;
}
// otherwise, just perform the "normal" left or right move
else
{
this.currentX += this.dX;
return this.dX > 0 ? Direction.EAST : Direction.WEST;
}
}
finally
{
// ensure we set the current values for the next move
this.currentY = nextValue;
}
}
else
{
// You know what to do here: vertical moving is "primary"
}
}
尝试对“((allDirections中的方向目录)”中的目录使用“随机”,以便它每次都检查不同的方向顺序并以之字形移动..
由于它始终沿相同方向检查北>南>西>东>东,所以它一直在直线上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.