Sometimes when you’re writing geometry-heavy code, it’s tempting to copy some stuff straight from a mathematical formula in a textboook, especially if you’re not much of a math genius and you just want something to work. But here’s how it can go unfortunately wrong:

Say you’re implementing rotation around the origin in 3D. The famous way to do it is with a rotation matrix, and everywhere you look, you’ll see these equations. Now after a little reminder about matrix multiplication, we just need to convert it to code. Simple, isn’t it?

public void rotate(double xRotation, double yRotation, double zRotation) { if (xRotation != 0) { this.y = this.y * Math.cos(xRotation) - this.z * Math.sin(xRotation); this.z = this.y * Math.sin(xRotation) + this.z * Math.cos(xRotation); } if (yRotation != 0) { this.x = this.x * Math.cos(yRotation) + this.z * Math.sin(yRotation); this.z = -this.x * Math.sin(yRotation) + this.z * Math.cos(yRotation); } if (zRotation != 0) { this.x = this.x * Math.cos(zRotation) - this.y * Math.sin(zRotation); this.y = this.x * Math.sin(zRotation) + this.y * Math.cos(zRotation); } }

If you can spot why it’s broken, you’re sharper than I am. Took me about a week[1] to figure out why my rotations weren’t working.

[1] Okay, I was doing other things during that week, but it did include several failed attempts at spotting the problem.