Skip to content

Instantly share code, notes, and snippets.

@ZeWaka
Created February 2, 2023 21:16
Show Gist options
  • Save ZeWaka/4314c3451c0b6f18e8f3d9bfc0c21b1f to your computer and use it in GitHub Desktop.
Save ZeWaka/4314c3451c0b6f18e8f3d9bfc0c21b1f to your computer and use it in GitHub Desktop.
#include <math.h>
int get_coord(int i, int center_x, int center_y){
if (i == 0) {
return (center_x, center_y);
}
int base = floor((sqrt(i) - 1) / 2) * 2 + 1; // side of the already filled square
int cur_i = pow(i - base, 2); // which tile are we on in this layer
int radius = (base + 1) / 2; // radius of this layer
int side = 2 * radius + 1;
int last_col_threshold = pow(base + 2, 2) - side; // at which i do we start filling the last column of this layer
if (cur_i < side) {
return (center_x - radius, center_y - radius + cur_i);
} // first column
else if (i >= last_col_threshold) { // last column
int j = i - last_col_threshold;
return (center_x + radius, center_y - radius + j);
}
else { // the rows
int j = (cur_i - side) / 2; // x-shift
int sign; // 1 if top row, -1 if bottom row
if ((cur_i - side) % 2 == 0) {
sign = -1;
} else{
sign = 1;
}
return (center_x - radius + j + 1, center_y + sign * radius);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment