This topic is 2155 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi,

I am forced to ask this shameful question here. I've build a quadtree structure which contains 2D triangles. Everything would be nice, cool and fast if only I would knew how to use it

My aim is to cast a 2D ray from given point with given direction, and get the closest triangle position. And my question is how should I approach that? Should I add my ray to quadtree and there find collision? Or should I aproach it different way?

##### Share on other sites

You need to traverse the quad-tree as follows:

1. start at root node.

2. intersect your ray with the root node's bounding box.

3. does it intersect it? if not, return (to the calling function) with no intersection (if you can't express "no intersection" in your algorithm, just use infinite distance)

4. if this is a leaf node:

- intersect the ray with all the triangles in the node, and return (to the calling function) the closest intersection

else:

- find out which children nodes the ray intersects, and sort them according to closest intersection (this is the trickiest part in my experience)

- recurse to step 2 for each child node, in order of intersection, until the closest triangle found is closer than the distance to a child's bounding box (in which case any triangle inside that child will be further away than the one you've already found, so there's no need to traverse it)

- return (to the calling function) the closest intersection you found

This is a recursive process, and will find the closest triangle intersecting the ray with complexity O(log(n)) where n is the number of triangles in your quadtree. You probably want to implement this with a stack instead of using recursion (at least once everything is working) for performance's sake. The really annoying part is getting the bounding box collisions right, I highly recommend you overlay your quadtree on top of your triangles using wireframe rectangles to debug any issues.

Edited by Bacterius

##### Share on other sites

Thank You for answer :) I actually was thinking about somthing similar but i thought it's not the best way to do it.

- find out which children nodes the ray intersects, and sort them according to closest intersection (this is the trickiest part in my experience)

I agree, that's the part that actually discouraged me, but it shouldn't be a problem for me (the real problem is that I am lazy ).

I also display grid already so I can see how structure looks like.

• 21
• 13
• 9
• 17
• 13