Skip to content

Basic Introduction

Vinicius Reif Biavatti edited this page Apr 16, 2021 · 7 revisions

Tutorial

This is the basic tutorial of RayCasting implementation. This is the easiest tutorial of the wiki. The tutorial is divided in session, that each session corresponds to some subject. The pre-requisites for this tutorial is just the little knowledge of:

  • Trigonometry
  • Basic Javascript
  • Basic Canvas Programming

Logic

RayCasting is a 3D projection of a 2D map, so, we will transform a number matrix (map) to a projection (screen) using the RayCasting method. The logic of RayCasting is basically throw rays to the direction of the player view. This is necessary to find the walls in the map and check the distance of the wall to calculate the size of the line we need to draw in the canvas. The map will be an integer number matrix with 1 (one) or 0 (zero) values where 0 (zero) represents the empty place and 1 (one) represents the wall.

For other tutorials we will use more numbers for the map matrix.

The projection will be drawed in the screen, from the left to the right. Every ray corresponds to a x-axis slice of the screen, so, with we have a screen with size 640x480, we will need to throw 640 rays to project the result.

For each throwed ray we have to calcule the direction of it to iterate the positions of this ray and find some wall. The initial ray position starts from the player position and follow forward in relation of the FOV (Field of view) of the player.

Image of the RayCasting logic in the 2D map matrix

Steps

The RayCasting is separated in some steps to organize the implementation of the logic. See below to understand what each step does:

  1. Define a ray angle in relation of player FOV
  2. Create a ray loop. This loop will iterate the screen width
  3. Get the sin and cos of the ray angle to discover the numbers to increment to follow forward with the ray
  4. Create a loop to check if the position of the ray is an wall. If the position is not a wall, increment with sin and cos values and check again
  5. After find a wall, get the distance between player coordinates and ray coordinates with pythagoras theorem
  6. Discover the wall height reversing the got distance in relation of the half height of the screen using divide operator
  7. draw the "ceiling" line from the top of the screen to the top of the wall height
  8. draw the "wall" line in relation of the wall height obtained
  9. draw the "floor" line from the bottom of the wall height to the bottom of the screen
  10. Repeat this process for every ray (x-axis screen coordinate)

So, basically, we will draw just lines!

Result

The result that we will get from this tutorial is the image below. This is a little strange, but it can be a good initial RayCasting implementation to understand the logic.

Raycasting result example