I’ve developed a function to calculate the exit angle of a projectile after it collides with a boundary/edge inside a rectangular space, based on the entry angle and the axis it is colliding with.
Given those two factors, the actual boundary is implied, since a projectile travelling at an angle of 315° (where 0°/360° sit at 3 o’clock) and colliding with a horizontal boundary (the x axis) must be colliding with the top boundary.
The current implementation came about through iterative refactoring of a much more verbose and redundant version, however I can’t vocalise exactly why some parts are necessary, but they appear to satisfy the requirements and I’m confident it works based on a number of tests.
function reflectAngle(angle, axis) { if (angle % 90 === 0) return (angle + 180) % 360; let reflected; let segment = (angle % 90) * 2; if (axis === 'X') reflected = angle + (180 - segment); else if (axis === 'Y') reflected = angle - segment; if (angle < 90) reflected += 180; return reflected % 360; }
Can this function be simplified or improved for readability?
It’s a fairly language agnostic function so I’m not heavily interested in JS-specific improvements, but happy to hear them.