Three.js get the 4 corner coordinates of a cube?

喜夏-厌秋 提交于 2020-06-25 21:10:22

问题


How do I get the 4 coordinates for the corners of a cube?


回答1:


If you are using the CubeGeometry (width, height, depth) and you positioned the cube somewhere, then your eight corners are at

position.x + width/2, position.y + height/2, position.z + depth/2
position.x + width/2, position.y + height/2, position.z - depth/2
position.x + width/2, position.y - height/2, position.z + depth/2
position.x + width/2, position.y - height/2, position.z - depth/2
position.x - width/2, position.y + height/2, position.z + depth/2
position.x - width/2, position.y + height/2, position.z - depth/2
position.x - width/2, position.y - height/2, position.z + depth/2
position.x - width/2, position.y - height/2, position.z - depth/2



回答2:


Here's a full implementation:

// Returns the positions of all the corners of the box
// Uses CSS ordering conventions: CW from TL.  First front face corners, then back.
THREE.BoxGeometry.prototype.corners = function(position){
  this._corners || (this._corners = [
    new THREE.Vector3,
    new THREE.Vector3,
    new THREE.Vector3,
    new THREE.Vector3,
    new THREE.Vector3,
    new THREE.Vector3,
    new THREE.Vector3,
    new THREE.Vector3
  ]);

  var halfWidth = this.parameters.width / 2, halfHeight = this.parameters.height / 2, halfDepth = this.parameters.depth / 2;

  this._corners[0].set(position.x - halfWidth, position.y + halfHeight, position.z + halfDepth);
  this._corners[1].set(position.x + halfWidth, position.y + halfHeight, position.z + halfDepth);
  this._corners[2].set(position.x + halfWidth, position.y - halfHeight, position.z + halfDepth);
  this._corners[3].set(position.x - halfWidth, position.y - halfHeight, position.z + halfDepth);
  this._corners[4].set(position.x - halfWidth, position.y + halfHeight, position.z - halfDepth);
  this._corners[5].set(position.x + halfWidth, position.y + halfHeight, position.z - halfDepth);
  this._corners[6].set(position.x + halfWidth, position.y - halfHeight, position.z - halfDepth);
  this._corners[7].set(position.x - halfWidth, position.y - halfHeight, position.z - halfDepth);

  return this._corners

}

THREE.Mesh.prototype.corners = function(){

  if (!this.geometry instanceof THREE.BoxGeometry){
    console.warn('Unsupported geometry for #corners()')
    return
  }

  return this.geometry.corners(this.position)

};


来源:https://stackoverflow.com/questions/15302603/three-js-get-the-4-corner-coordinates-of-a-cube

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!