[英]How does one find the index of an object in a list whose x and y position value match a given x and y
I am creating a game that uses a tile system. 我正在创建一个使用图块系统的游戏。 Each tile is an object that has a Vector2 for its position.
每个图块都是一个对象,其位置带有Vector2。 I have every tile in List.
我在清单中有所有磁贴。
I have another bit of code that generates a bunch of Vector2's where trees should be placed on the grid of tiles. 我还有另一段代码可以生成一堆Vector2,其中应将树木放置在瓷砖网格上。 Every tree position is in a Vector2 in a List
每个树的位置都在列表的Vector2中
My question is, how do I find the index of the tile that has an exact match of its coordinates in the List of tree coords. 我的问题是,如何在树坐标列表中找到与其坐标完全匹配的图块索引。 Once I find that I can then tell that tile object in the list to turn its treePresent boolean to true.
一旦找到,便可以告诉列表中的该平铺对象将其treePresent布尔值设为true。
The tiles' gridPosition.X and gridPosition.Y: 0(1,9) 1(1,10) 2(2,1) 3(2,2) 瓦片的gridPosition.X和gridPosition.Y:0(1,9)1(1,10)2(2,1)3(2,2)
The trees' treePosition.X and treePosition.Y : 0(1,9) 1(2,2) 树木的treePosition.X和treePosition.Y:0(1,9)1(2,2)
I could then say: tileList[0].treePresent=true; 然后我可以说:tileList [0] .treePresent = true; tileList[3].treePresent=true;
tileList [3] .treePresent = true;
A game using a tile system should NOT use a dynamic system (a list) for keeping track of the tiles. 使用图块系统的游戏不应使用动态系统(列表)来跟踪图块。 I am assuming by "tile system" you refer to the entire game world/map divided into a 2D grid.
我假设“平铺系统”是指将整个游戏世界/地图划分为2D网格。 The reason for this is two fold:
原因有两个:
So the solution is simple: Make a 2D array of tiles. 因此,解决方案很简单:制作2D瓷砖阵列。 The first dimension is for your x-coordinates, the second is for y.
第一个维度用于x坐标,第二个维度用于y。
For example: worldData[x][y] (or equivalent to the language of your choice). 例如:worldData [x] [y](或等效于您选择的语言)。 In this manner, finding a tile is pretty instant.
以这种方式,查找图块非常容易。 Here if I want tile (a,b), I simply call worldData[a][b].
在这里,如果我想要平铺(a,b),我只需调用worldData [a] [b]。 No looping or comparisons needed.
无需循环或比较。
Any questions? 任何问题?
Try 尝试
tileList.Where(t => treeList.Contains(t.Position));
If you are moving things around, beware that this compares for float equality, which can cause problems. 如果要四处走动,请注意,这会比较浮点数相等,这会引起问题。
You could also make a 2 dim list and reference the tile just by the tree position. 您还可以制作一个2暗列表,并仅通过树的位置引用图块。 Unless you're changing your grid size you shouldnt need to use a dynamic list and instead can create a 2 dimensional array
除非您更改网格大小,否则不需要使用动态列表,而是可以创建二维数组
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.