AlignedBoxGeometry (box from x1,y2,z1 to x2,y2,z2)

Hi! I’m new to three.js

I found a very useful function. It creates a mesh, and it works well.

I want to procedurally draw a model and merge its geometry into one mesh.

I’m trying to rewrite the function so that it returns a geomtry instead of a mesh, but there is no copy function in geometry.
And without the position.copy(a) line, the procedure doesn’t work correctly.

Original procedure:

class AlignedBox extends THREE.Mesh {
  constructor(w, h, x1, y1, z1, x2, y2, z2, color = '888888') {
    let a = new THREE.Vector3(x1, y1, z1)
    let b = new THREE.Vector3(x2, y2, z2)
    let l = a.distanceTo(b)
    let g = new THREE.BoxGeometry(w, h, l).translate(0, 0, l * 0.5)
    let m = new THREE.MeshLambertMaterial({ color: '#' + color })
    super(g, m)
    **this.position.copy(a)**
    this.lookAt(b)
  }
}

My procedure:

const AlignedBoxGeometry =  (w, h, x1, y1, z1, x2, y2, z2) => {
    let a = new THREE.Vector3(x1, y1, z1)
    let b = new THREE.Vector3(x2, y2, z2)
    let l = a.distanceTo(b)
    let g = new THREE.BoxGeometry(w, h, l).translate(0, 0, l * 0.5)
    **this.position.copy(a)**
    g.lookAt(b)
    return g
  }
}

Perhaps lookAt also doesn’t work correctly in my case.

https://jsfiddle.net/mt2wrqb9/

This should do the trick:

function AlignedBoxGeometry(w, h, x1, y1, z1, x2, y2, z2) {
  let a = new THREE.Vector3(x1, y1, z1)
  let b = new THREE.Vector3(x2, y2, z2)
  let l = a.distanceTo(b)

  return new THREE.BoxGeometry(w, h, l)
    .translate(x1, y1, l * 0.5 + z1)
    .lookAt(b.sub(a))
}

https://jsfiddle.net/gef0udco

2 Likes

thank you very much, it works.

1 Like