# Finding closest object to a location within a specific perpendicular distance to direction vector

I have a location and a direction vector indicating facing, I want to find the closest object to that location that is within some tolerance distance (perpendicular distance) to the ray formed by the location and direction vector. Basically I want to get the object that is being aimed at.

I have thought about finding all objects within a box and then finding the closest object to my vector from them results, but I am sure that there is a more efficient way.

The Z axis is optional, the objects are most likely within a few meters of the search vector.

• Define "in that specific direction." How close to that specific direction? How wide of an angle do you want to cast? Etc. Commented Jul 7, 2012 at 20:32
• Seems like the best way is a cylinder-point intersection test. Also your language of using vectors as points and directions is going to make a math person slap you. Commented Jul 7, 2012 at 20:35
• What Byte56 said. You can cast a ray in the direction you want to see what it intersects with too. Commented Jul 7, 2012 at 21:22
• As Byte56 said, just by using Object Oriented Bounding Boxes you could speed up things and "cull"away some unnecessary point-to-line distance queries. Point in cylinder is in this case equivalent to a point-to-line distance query by setting your line as the line passing through (SearchPoint, SearchPoint + SearchVector) and then compute distances from the vertices of the OOBBs to this ray. Commented Jul 8, 2012 at 11:37

This may not be optimal, but it might give you a start.

Let O be the origin of the ray and D is the NORMALISED direction. The parameteric equation of the line is P = O + tD

For a given point Q, we can find a value of t which will give us the point on the line closest to Q

t = D . (Q-O)

(that's a dot product)

Plugging it into the equaton of the line you can find the point on the line that's closest to Q:

C = O + t D

Then you can get the length of Q-C and test if it's within your desired threshold. I reccommend testing squared values to avoid doing a load of square roots.

Also, you can discard points that give a negative t value (the are behind the observer) and the smallest value of t will give the closest intersection.

Hope that's clear enough. It will work in 2D or 3D.