简体   繁体   中英

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. 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;

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:

  1. You potentially will use more memory to store a full map of data. If there is really not much going on in your world, and you will mostly (80% or much more) only see a blank/default background tile, then this rule may be proven invalid. However, for all cases with reasonable amount of data (which is what I am assuming here), you will use more memory as you have to store the tile type, and x&y coordinates, as opposed to just storing tile type.
  2. Dynamic data structure is inefficient. Fetching tile data will take long in this manner, as you have to loop through your entire list to find a specific tile. So if you want tile (a,b), you have to loop through all your tiles (stopping once you have found the right tile), and comparing each (x,y) of every tile to (a,b). Doesn't sound very efficient, does it?

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?

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. Unless you're changing your grid size you shouldnt need to use a dynamic list and instead can create a 2 dimensional array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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