I am trying to convert a 2D grid of (x, y) points to a sphere in space. I loop through all of the points in the grid and set the value to an object {x: someX, y: someY, z: someZ}. But for some reason, the value I get inside the loop is different from the value outside. Do I have a typo or is this something about JS I don't understand yet? Here is the exact section causing issues:
for (let y = 0; y < GRID_WIDTH; y++) {
for (let x = 0; x < GRID_WIDTH; x++) {
points[y][x] = grid2Sphere(x, y); //returns {x: someX, y: someY, z: someZ}. This works.
console.log(points[y][x]); // This logs the correct values
}
console.log(points[y]); // This is always equal to the row where y = 0. It's as if everything that happened in the inner loop did not get set.
}
For those interested, here is the entire file. I am using p5.js:
let R;
let points;
const GRID_WIDTH = 20;
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
stroke("#000");
R = 100;
angleMode(RADIANS);
points = new Array(GRID_WIDTH).fill(new Array(GRID_WIDTH).fill({}));
// Calculate and draw each point.
for (let y = 0; y < GRID_WIDTH; y++) {
for (let x = 0; x < GRID_WIDTH; x++) {
points[y][x] = Object.assign({}, grid2Sphere(x, y));
console.log(points[y][x]);
}
console.log(points[y]);
}
drawPoints(points);
}
function draw() {
noLoop();
}
function drawPoints(pArray) {
for (let y = 0; y < GRID_WIDTH; y++) {
for (let x = 0; x < GRID_WIDTH; x++) {
let p = pArray[y][x];
point(p.x, p.y, p.z);
}
}
}
function grid2Sphere(x, y) {
var radX = map(x, 0, GRID_WIDTH - 1, -1 * PI * R, PI * R);
var radY = map(y, 0, GRID_WIDTH - 1, -1 * PI / 2 * R, PI / 2 * R);
var lon = radX / R;
var lat = 2 * atan(exp(radY / R)) - PI / 2;
var x_ = R * cos(lat) * cos(lon);
var y_ = R * cos(lat) * sin(lon);
var z_ = R * sin(lat);
return {x: x_, y: y_, z: z_};
}