在三维空间中,
Spherical构造函数用于描述球坐标系中的一个点。球坐标系通过半径、极角(phi)和赤道角(theta)来定义一个点的位置。
在 Three.js 中,Spherical对象本身并不会直接表示场景中的实际位置。它仅仅是一个工具,用来将球坐标转换为三维空间中的笛卡尔坐标 (x, y, z)。生成的Spherical对象需要通过其他函数来转换为实际的三维坐标,才能用于设置物体的位置。
具体来说,Spherical表示的是一个球坐标(通过radius、phi、theta描述的点),但是如果你希望在 Three.js 场景中表示这个点的位置,需要将球坐标转换为三维的笛卡尔坐标,并将这些坐标应用到物体的position属性上。
Spherical 有三个属性,六个方法
在使用 THREE.Spherical 进行球坐标和笛卡尔坐标转换时,默认的中心点是 (0, 0, 0)。所有的计算,例如半径 (radius)、极角 (phi) 和赤道角 (theta),都是基于这个原点进行的。
示例:使用 Spherical 设置物体或相机的位置 该示例中是将相机设置为围绕着0,0,0 半径为 10 极角为 Math.PI / 4 赤道角为 Math.PI / 4 的位置
// 距离原点的距离
const radius = 10;
// 极角
const phi = Math.PI / 4;
// 赤道角
const theta = Math.PI / 4;
// 创建一个球坐标对象
const spherical = new THREE.Spherical(radius, phi, theta);
// 将球坐标转换为相机的笛卡尔坐标
camera.position.setFromSpherical(spherical);
// 让相机看向原点
camera.lookAt(new THREE.Vector3(0, 0, 0));
设置物体的位置:示例中的物体是相对于中心点 (0, 0, 0) 给出的,使用半径为 5、极角为 phi、赤道角为 theta 来确定其在三维空间中的具体位置。
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(1), // 创建一个球体物体
new THREE.MeshBasicMaterial({ color: 0xff0000 })
);
const radius = 5; // 距离原点的距离
const phi = Math.PI / 3; // 极角
const theta = Math.PI / 6; // 赤道角
// 创建一个球坐标对象
const spherical = new THREE.Spherical(radius, phi, theta);
// 将球坐标转换为物体的位置
mesh.position.setFromSpherical(spherical);
// 将物体添加到场景中
scene.add(mesh);
属性
- radius : Float 距离原点的距离
- phi : Float 极角
- theta : Float 赤道角
方法
- clone () : Spherical 返回一个新的球坐标,新的球坐标与该球坐标具有相同的 radius、phi和theta。
- copy ( s : Spherical ) : this 复制所传入的球坐标的radius、 phi 和theta属性到该球坐标中。
- makeSafe () : this 将极角 phi 的值限制在0.000001 和 π - 0.000001 之间。
// 创建一个 Spherical 对象,极角超出范围,半径为负值
const spherical = new THREE.Spherical(-5, -Math.PI / 2, Math.PI / 2);
// 输出原始值
console.log(spherical); // Spherical { "radius": -5, "phi": 0.000001, "theta": 1.5707963267948966 }
// 调用 makeSafe() 修正 phi 和 radius
spherical.makeSafe();
// 输出修正后的值
console.log(spherical); // Spherical { "radius": -5, "phi": 0.000001, "theta": 1.5707963267948966 }
- set ( radius : Float, phi : Float, theta : Float ) : this 从Vector3中设置球坐标的radius、phi和theta值。
- setFromVector3 ( vec3 : Vector3 ) : this 从Vector3中设置球坐标的radius、phi和theta值。
- setFromCartesianCoords ( x : Float, y : Float, z : Float ) : this 从笛卡尔坐标系中设置球坐标的radius、phi和theta值。
// 创建一个 Spherical 对象
const spherical = new THREE.Spherical();
// 使用笛卡尔坐标 (3, 5, 2) 设置球坐标
spherical.setFromCartesianCoords(3, 5, 2);
// 输出球坐标
console.log(spherical);
// 结果:Spherical { "radius": 6.164414002968976, "phi": 0.6247538687650431, "theta": 0.982793723247329 }