Reputation: 75
I am creating a game that uses a tile system. Each tile is an object that has a Vector2 for its position. 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. Every tree position is in a Vector2 in a List
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.
The tiles' gridPosition.X and 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)
I could then say: tileList[0].treePresent=true; tileList[3].treePresent=true;
Upvotes: 1
Views: 1082
Reputation: 704
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. The reason for this is two fold:
So the solution is simple: Make a 2D array of tiles. The first dimension is for your x-coordinates, the second is for y.
For example: worldData[x][y] (or equivalent to the language of your choice). In this manner, finding a tile is pretty instant. Here if I want tile (a,b), I simply call worldData[a][b]. No looping or comparisons needed.
Any questions?
Upvotes: 3
Reputation: 15
You could also make a 2 dim list and reference the tile just by the tree position. Unless you're changing your grid size you shouldnt need to use a dynamic list and instead can create a 2 dimensional array
Upvotes: 2
Reputation: 43056
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.
Upvotes: 2