Algorithm for 2D Raytracer

I am afraid that the kind of ray trace app you are proposing is a bit more misleading than to use a real 3D ray-tracer.

  • 2D ray tracers are used a bit differently
  • and this may confuse your audience a lot

I would try to chose a more native 2D ray-trace usage like:

  1. Optic simulation

    This is used to simulate lens and mirrors optics. This image is from one of my ancient 2D ray-trace simulations:

    optic sim
    img

    1. Store your world

      You’ve got a lens in the form of polylines + diffraction index and mirrors also as polylines. You have the world diffraction index

    2. cast R,G,B rays from source of light

      Cast important ones only or all of them. Use Snell’s law to simulate optics

    As you can see the chromatic error is visible (each color has its own wavelength so the diffraction index is different). You can also use MultiBand rendering.

    I used this to tune custom optic systems. If you add drag & drop capability you’ve got Optic Lab.

  2. Wolfenstein demo

    This pseudo 3D game used a 2D ray casting engine. See Wiki: Wolfenstein_3D_engine. This image was taken from this link:

    wolf3d

    1. first draw the floor and ceiling/sky as 2 half screens (screen divided by horizon)
    2. then you’ve got a 2D map of your maze/world (right)

      So cast rays from your current position in all visible directions (similar to your image but usually a 60 degree view is used). Rays must be done with subpixel (cell) precision. Where your ray hit the wall (on map) obtain the subpixel (cell) position. It indicates which part of wall texture is hit

    3. draw the appropriate column (vertical line) on the screen for each ray hit

      The size and scale of it is determinated by the distance from the ray origin. The fish eye correction is applied — if my memory serves it was done by using only perpendicular distance (multiply distance by cos(ray_angle - player_angle)).

    Here’s an example of what I busted out for fun just now:

    my Wolf3D

    It was done in C++ with pure GDI (using the bitmap scan line only), no other 3th party libs at all. It uses a single texture, diffuse + ambient lighting, 2D raycasting. Has 2 bitmaps (screen, texture-atlas) and a single 2D map. The code is less then 9 KByte including rems. It is controlled by keyboard only (mouse is used to edit the maze in the map subwindow).

    Here animated GIF example:

    Wolf3D

    If you’re interested see this related QA:

Leave a Comment