I am currently rewriting Chris Wellons’s racing simulation in rust as a training exercise. His program is really nice in that it is visual, interesting and well under 500 lines of Code - really inspiring. (I wouldn’t have minded speaking variable names and comments though).
Rust is still hard for me, I am mostly fighting the borrow checker. But the extremely helpfully error-messages and Stackoverflow mostly help me get over it.
There is a magical moment in creating simulations: The point were errors don’t break the simulation, they just cause strange behavior. The most famous example is probably the drunk cats in dwarf fortress.
In my simulation the problem was that I just couldn’t get the driver to drive the course without hitting a wall. It should steer into the direction that has the most free space and adjust it’s speed according to how much free road is ahead (more on that later).
(The map is drawn by me and it is only 300x200, so it might look blury on your screen.)
These errors are so great because you can try to reason within the logic of the simulation. Is the car going to fast/slow? Is the turning radius to big? Does the driver act too sudden on curves? Or perhaps the map is to difficult and the turns are too sharp?
After trying a few things out I decided to visualize the field of view of the the car. As is in the original simulation, the car does 3 raycasts: to the left, forwards and to the right. It then decides how to steer the car based on how much space it has in each direction.
Here is what the car sees on the course:
It’s immediately obvious that something is wrong here. There was a sign error in the y-axis in the calculation for the raycasts. It is a bit like the driver was looking at the street over a mirror.
I love that kind of debugging. Instead of error messages, stacktraces and debuggers you think about the car, the map and what the driver sees.
Here is the fixed version, just a minus sign away: