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

后端 未结 3 1660
清酒与你
清酒与你 2021-02-07 16:03

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

相关标签:
3条回答
  • 2021-02-07 16:27

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

    0 讨论(0)
  • 2021-02-07 16:34

    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.

    0 讨论(0)
  • 2021-02-07 16:41

    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

    0 讨论(0)
提交回复
热议问题