简体   繁体   中英

Best data structure to hold a group of coordinates inside a really big rectangle?

I have an abstract representation of a map with, lets say, 5.000.000 different integer coordinates on the X and Y coordinates, so it is a really big 2d rectangle.

And then, inside that variable-sized rectangle, I have several objects (characters, monsters, npcs). A player can select a position of this rectangle, and I have to check if there is a monster or a character on said position.

So far, I made a custom class called GameMatrix with columns and rows, and said columns has 3000x2000 positions (the area view of a character).

When a player of my game clicks on said coordinate, I have to do a foreach() of every element inside the matrix, and most of the times it is empty.

Is there a better way to solve this? Specifically, I am asking on what is the best way to, having a really big rectangle and a coordinate, check if there are objects inside said coordinate in an efficient way.

Forgot to mention, but this is done in the server-side several times per miliseconds. So I need a lot of performance.

Edit: Forgot to mention, I am using C#.

You should use a quad-tree implementation, unless the number of items in the grid is really small (like a couple of dozens items), in which case a linear search (brute force inspecting all of them at the same time) is probably the best choice.

See here

http://en.wikipedia.org/wiki/Quadtree

Note that a quad tree can be queried very quickly and efficiently, but updates are a bit more costly, that is if your items move a lot across your map, this becomes more complicated to do with a good performance.

I would recommend just trying the simplest solution first and worry about the optimization later.

Try using an array. Improve your solution as you go. A list or hash map might be interesting too depending on your setup.

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