1 Motivation
Imagine a 2D grid world with obstacles and walls in the form of blocks. Imagine a robot with a
laser sensor inside this world. I am given the position of the robot and the angle at which laser is emitted, I want to know the grid cell with which this laser collides and the exact position where it
collides.
I had a look at Stage library, but I was not able to understand the code in world.cc properly. It cites a book
called Graphics Gems IV to which I didn’t have access. So to understand the algorithm, I derived
it from first principles, which you will see is not very difficult.
2 Notation
Let the size of grid cells be denoted by
and the unit vector along the ray be denoted by
.
The distance from the nearest grid walls in the direction of ray be denoted by
.
Assume that the ray is as given in Fig 1 and intersects consecutive grid lines at
and
.
3 Derivation
For ray tracing we want to find all the grid cell from which the
ray crosses. Since we can do it recursively, support we are at point
and want to find point
. The first question to
be answered is whether
lies on the Y-axes or X-axes. In the case of given diagram,
lies on
the Y-axes, or we have taken one step along X-axes. However, if the slope was greater than
than the line would have
crossed the gridline earlier
than . This can be easily
detected by the sign of .
We take a step along X-axes when
or
Now, we just need a recursive formula for
and . Let’s
compute and
for this case when
we know that .
Aren’t we lucky that we got a formula of
in terms of
and ?
Both the terms we already knew and needed to compute for comparison. Also note that
is simply
.
Also doesn’t the fraction looks
something meaningful? Note that
is proportional to
which is makes me think it in terms of distance to next gridline upon velocity. This
term is nothing but time to collision to nearest gridline. Lets denote this terms as
. We can also
think of as
maximum possible time to collision when travelling along X axes. Using this simpler notation our
recursive formula are:
So the complete recursive formula can be written as:
Extension to 3D case is trivial: