Get list of all positiones between two Vector3

64 Views Asked by At

So I want a list of all positions if I give two positions(Vector3) in Javascript.

The Image is an example. I have two positions, p1 and p2. Now I need an algorith that gives me the positions of all cubes in that space. The numbers do not need to be decimal numbers. image

I tried this:

p1 = new Vector3(-1,-1,3)
p2 = new Vector3(3,3,1)

var result = []

for(var x = 0; x < p2.x+1; x++){
    for(var y = 0; y < p2.y+1; y++){
        for(var z = 0; z < p2.z+1; z++){
            result.push(new Vector3(p1.x+x,p1.y+y,p1.z+z))
        }
    }
}

But it doesnt work with negative numbers.

1

There are 1 best solutions below

2
On BEST ANSWER

We just need to add an helper function that returns an iterable array containing all the values between a certain range :

// Just to work in the snippet
class Vector3 {
  constructor(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z
  }
}

const p1 = new Vector3(1092, 32, -1120)
const p2 = new Vector3(1084, 36, -1120) 

const result = []

const createIterator = (a, b) => {
  const min = Math.min(a, b)
  const max = Math.max(a, b)

  // creates an array of the size of the diff betwenn min and max + 1
  // fill it with 0s to make it usable
  // map each el to its index offset by min
  return (new Array(max - min + 1)).fill(0).map((_, i) => min + i)
}

// iterate through all xs, ys, and zs
createIterator(p1.x, p2.x).forEach(x => {
  createIterator(p1.y, p2.y).forEach(y => {
    createIterator(p1.z, p2.z).forEach(z => {
      result.push(new Vector3(x, y, z))
    })
  })
})

console.log(result)