2 min read

ask me about atan2

The semester is done, so I’ve turned to something light and fun: revisiting the packages miner and craft for R programming with Minecraft, created at the 2017 ROpenSci UnConf. (See my past posts on the topic: ROpenSci Unconf 2017, miner and craft, and writing text in Minecraft with R. Also see our ebook, Programming R with Minecraft.)

I first wanted to see if it all still worked, particularly as the RaspberryJuice plugin which we rely on is no longer under development. So that meant firing up a minecraft server on my laptop, and on a Raspberry Pi, and in a Docker container. (Ugh, installing docker was a pain in the ass. In the end I got it to work, but I’m not sure how. Finding and installing the right version of Java was not so fun either.)

Anyway, I was working on incorporating a bunch of code that Felix Ling had sent me years ago. In particular, I was puzzling over his function to build a set of stairs, which would sometimes put them behind me instead of (as intended) in front of me.

It turns out our miner::getPlayerRotation() function gave different results depending on whether player_id was specified, but only for some orientations. Underneath the hood, we call the API function entity.getRotation() if player_id is specified but player.getRotation() if it’s not, and the latter was giving crap results for some orientations.

So I used miner::setPlayerRotation() in a loop over angles (making my Minecraft player spin around in a circle) and polled the getPlayerRotation() function with and without specifying player_id, and also miner::getPlayerDirection() which returns a unit vector to indicate direction, rather than an angle. (Note that there’s a related function miner::getPlayerPitch() for determining the up/down angle of where you’re facing.)

I can’t tell you how long I spent puzzling over the conversion between Cartesian and polar coordinates. Isn’t this easy? $x=r sin(\theta)$ and $y = r cos(\theta)$, and then to go back you have $r = \sqrt{x^2 + y^2}$ and $\theta = atan(y/x)$, right?.

But WTF $atan(y/x)$ only returns a value in $(-\pi/2, \pi/2)$, not the whole circle.

Finally, I turned to the wikipedia page on polar coordinates and learned about $atan2(y,x)$, which I’m sure I’d never heard of before.

So it’s not really been what I’d call “light”, but it’s definitely been fun. And I’m learning about docker (though it likely won’t seem like I did the next time I have to revisit it), and math, and how to get fences to connect up, and I’m making a mess of my Minecraft world.

Minecraft world after messing with the miner package