Tuna Gül

Systems

Line-of-Sight Archive

2D shadow casting in pygame: the block grid becomes a few long edges, rays go to every corner and just past it, and the lit area is drawn from where they hit.

Role
Author
Period
Oct–Dec 2020
Team
Solo
Stack
Python · pygame

Code ↗

Line-of-Sight

What I did

A small weekday project: a pygame scene where you place blocks with the mouse (left click adds, right click removes) and press space to switch on a light that follows the cursor.

How it works

  • The grid is turned into edges: every block side that faces empty space, with neighbouring sides on the same line merged into one edge. A row of ten blocks becomes four edges.
  • From the light, three rays go to every edge corner: one straight at it and two that pass it by 0.0001 rad on either side, so the light can slip past the corner.
  • Each ray stops at the nearest edge it crosses (line–line intersection). Sorted by angle, the hit points draw the lit area as a fan of triangles.
  • Based on The Coding Train's ray casting video and One Lone Coder's shadow casting video.

Gallery

Blue blocks with green merged edges and cyan corners; white rays from a light in the middle, the lit area in grey.
Illustration of the method, redrawn for this page in the program's own colours. Not a screenshot of the original.