Skip to content

Raycasting

sarahmss edited this page Jul 3, 2022 · 7 revisions

Raycasting

Raycasting is a rendering technique to create a 3D perspective in a 2D map. it 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. image


Basic Idea:

  • Map is a 2D square grid
  • Either grid can be 0: no wall or 1: Wall
  • For every pixel in screen, send out a ray that starts at the players's position and depend on both:
    1. Player's looking direction
    2. x-coordinate of the screen

Attributes

  1. Player's height
    • half of the wall height
  2. Player's field of vision (FOV)
    • determines how wide the player sees the world in front of him/her.
  3. Player's position
    • To put the player inside the world, we need to define the player's x and y coordinates.
  4. Projection plane's dimension
    • to project what the player sees into the projection plane we can use a 320X200 rectangle
  5. Relationship between player and project plane FOV

ALgorithme

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)

Useful links

Raycasting.pdf

Clone this wiki locally