-
I got this working. Specifically, getting the distance from the cosine to be one-sided — meaning if the point is on one side of the wave, get the distance to the "next" wave, rather than the closest wave. (Though I'm not actually doing that; just something that looks the same as that.)
Last night, I thought I'm way too tired to think think this through; better to just do this after sleeping. I did just that despite kinda not really believing that. And it did actually go better the next day!