简体   繁体   English

用于基于网格的运动的多维数组

[英]Multidimensional Array For Grid Based Movement

I am practicing my programming skill using Unity3D. 我正在使用Unity3D练习编程技能。 I have a grid set up that has coordinates in an x,y type of setup. 我有一个网格设置,其中的坐标以x,y类型设置。

[0,0] to [10,10]

With all the numbers in between (IE 5,5 would be close to center of the map). 介于所有数字之间(即IE 5,5将接近地图中心)。

The thing that I am trying to do now is figure out a mathematical formula to calculate the coordinates my character can move. 我现在要做的是找出一个数学公式来计算角色可以移动的坐标。 If the character is at position 5,5 and has a movement radius of 2 what is the most efficient way to return a list or an array of coordinates my character can move to? 如果角色在位置5,5处并且移动半径为2,那么返回该角色可以移动到的列表或坐标数组的最有效方法是什么? Every single grid square is its own object and have public variables for its X and Y so once I have the available results actually using them in the code isn't hard. 每个单独的网格正方形都是其自己的对象,并且具有针对其X和Y的公共变量,因此一旦获得可用结果,在代码中实际使用它们就不难了。

Here's what I'm trying so far (I'm ignoring the out of range possibility for right now, that's an easy fix): 到目前为止,这是我正在尝试的操作(我现在暂时忽略了超出范围的可能性,这很容易解决):

for(int x = currentGridSquare.xCoord - myMovementRange; 
x <= currentGridSquare.xCoord + myMovementRange; x++){
for(int y = currentGridSquare.yCoord - myMovementRange;
    y <= currentGridSquare + myMovementRange; y++)
{
    //Starting at 5,5 with a movement range of 2 should
    //start this process at the value of 3,3 which
    // is incorrect
}
}

I may be too tired to actually calculate a formula for this but I've been searching and haven't come across anything so if anyone's had experience with this and knows a quick way to do it I would be greatly appreciative. 我可能不愿意为这个计算一个公式,但是我一直在搜索并且没有发现任何东西,因此,如果有人对此有经验并知道一种快速的实现方法,我将不胜感激。

Update: The values that I am expecting this to return would be coordinates. 更新:我期望这将返回的值是坐标。 In this example starting at 5,5, the values I'd want back would be [3,5],[4,4],[4,5],[4,6],[3,5],[4,5],[5,5],[6,5],[4,6],[5,6],[6,6] and [5,7] 在此示例中,从5,5开始,我想要返回的值将为[3,5],[4,4],[4,5],[4,6],[3,5],[4 ,5],[5,5],[6,5],[4,6],[5,6],[6,6]和[5,7]

So I used formula Ben provided and came up with: 因此,我使用了Ben提供的公式并得出:

foreach(var gridSquare in allGridSquares)
{
   if( (Mathf.Abs(myX - gridSquare.Xcoord) + (Mathf.Abs(myY - gridSquare.Ycoor) >= myMovementValue)
   {
        gridSquare.activate();
   }

}

I know that if the grid starts getting bigger than the distance formula will be more complicated and I will update this later if that's the case but for the size of my grid this works wonderfully. 我知道,如果网格开始变大,则距离公式会变得更加复杂,如果是这种情况,我将在稍后进行更新,但是对于我的网格大小而言,它的工作效果非常好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM