What is a good data structure for storing and searching 2d spatial coordinates in Java

感情迁移 提交于 2021-01-20 19:17:28

问题


I am currently writing a plugin for a game where one feature includes the ability to set areas defined by 2 two dimensional coordinates ( The upper left and lower right areas of a rectangle). These regions are then to be stored, and will have various other data associated with each region. As the player is moving about the world, I need to determine when he enters one of these regions from only the coordinates of the player, and the method of doing so must be efficient, as this will end up being called hundreds of times per second.

Are there any data structures that can efficiently support this kind of search, and if so, where can I find documentation on it, to either find a java implementation to use, or if necessary, implement it myself?

I also want to note, I found a few tree structures that only seemed to support bulk-loading, but I must be able to add and remove values from this structure in real time.


回答1:


A good datastructure for determining collision in a part of space is the quad-tree datastructure. The quad-tree recursively divides a space according to the number of elements in a given area. Thus it can do a search if coordinates are inside a region in logarithmic time.

EDIT: I have found an implementation here but no license information is given.




回答2:


In the one-dimensional case, a suitable data structure is the interval tree.

To solve the two-dimensional cast, you can either use an interval tree to quickly find those rectangles that contain the point in at least one dimension, and check the second dimension for each of them (which might already be fast enough), or use the generalizations to many dimensions the Wikipedia article sketches briefly (though I must admit that I did not understand that generalization on the first read).

Assuming the player moves slowly (i.e. the number of region enter or leave events is small compared to the number of regions) the following approach might be more efficient: Keep a search tree of the x-coordinates where rectangles begin or end, and an a similar tree for the y-coordinates. If a player enters or leaves a region, he must have crossed the x or y coordinate of a boundary point. That is, you would do a range query on the x search tree for the range [old_x, new_x], and check each of these rectangles. Do the same for the y-direction (not reporting duplicates).




回答3:


To implement coordinates you can use Point2D in a class that implements the functionality you're looking for:

http://download.oracle.com/javase/6/docs/api/java/awt/geom/Point2D.html



来源:https://stackoverflow.com/questions/6179635/what-is-a-good-data-structure-for-storing-and-searching-2d-spatial-coordinates-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!