Skip to content

几何变换

我们有时会想给一个几何体移动位置,缩放,旋转,可通过如下方式操作

  1. 通过调用Object3D类中的实例方法
  2. 通过物体的positionrotationscale属性

1.Object3D实例方法

所有的物体都继承自Object3D类,因此可以调用一些方法实现几何变换

1.1 位移

实现位移可以调用Object3D类中的translate相关的方法

如下有一个立方几何体

js
const cubeGeometry = new THREE.BoxGeometry(2, 2, 2) 
const cubeMaterial = new THREE.MeshLambertMaterial({
    color: 0x00ffff,
    shading: THREE.SmoothShading,
})
const cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
scene.add(cube)

image-20241014111426138

1.1.1 translateX()

沿X轴位移

js
cube.translateX(5)

image-20241014111310866

1.1.2 translateY()

再往Y轴位移

js
cube.translateY(5)

image-20241014111321509

1.1.3 translateZ()

再往Z轴位移

js
cube.translateZ(5)

111

1.1.4 translateOnAxis()

自定义轴位移

js
cube.translateOnAxis(new THREE.Vector3(1,1,1), 5)

PixPin_2024-10-12_17-02-30

1.2 旋转

实现位移可以调用Object3D类中的rotate相关的方法

选择的角度都是以弧度制为单位,Math.PI/180就是1度,Math.PI/180*45就是45度

或者可以使用MathUtils对象上面的方法

js
// 角度转弧度
degToRad(degrees: Float): Float

// 弧度转角度
RadTodeg(radians: Float): Float

1.2.1 rotateX()

绕x轴旋转

PixPin_2024-10-14_11-12-25

1.2.2 rotateY()

绕y轴旋转

PixPin_2024-10-14_11-18-01

1.2.3 rotateZ()

绕Z轴旋转

PixPin_2024-10-14_11-18-26

1.2.4 rotateOnAxis()

以该物体的中心为原点,根据传入的参数确定一个轴,根据此轴旋转

js
cube.translateY(2)

const animation = () => {
    requestAnimationFrame(animation)
    cube.rotateOnAxis(new THREE.Vector3(0, 1, 0), (Math.PI / 180) * 1)

    renderer.render(scene, camera)
    controls.update()
}
animation()

PixPin_2024-10-14_14-23-55

1.2.5 rotateOnWorldAxis()

以世界坐标的中心为原点,根据传入的参数确定一个轴,根据此轴旋转

js
cube.translateY(2)

const animation = () => {
    requestAnimationFrame(animation)
    cube.rotateOnAxis(new THREE.Vector3(0, 1, 0), (Math.PI / 180) * 1)

    renderer.render(scene, camera)
    controls.update()
}
animation()

PixPin_2024-10-14_14-23-55

2.通过属性

Object3D对象上有positionrotationscale三个属性,这三个属性都是一个Vector3

所以可以查看Vector3对象的实例方法

js
const mesh = new THREE.Mesh(geometry, material);

1.向量赋值

js
// 位置
mesh.position=new THREE.Vector3(0,0,0)
// 旋转
mesh.rotation=new THREE.Vector3(0.5 * Math.PI,0,0)
// 缩放
mesh.scale=new THREE.Vector3(2,0,0)

2.属性赋值

js
// 位置
mesh.position=new THREE.Vector3(0,0,0)
// 旋转
mesh.rotation=new THREE.Vector3(0.5 * Math.PI,0,0)
// 缩放
mesh.scale=new THREE.Vector3(2,0,0)

4.set()方法

js
// 位置
mesh.position.x = 0;
mesh.position.y = 0;
mesh.position.z = 0;
// 旋转
mesh.rotation.x = 0.5 * Math.PI
mesh.rotation.y = 0.6 * Math.PI
mesh.rotation.z = 0.7 * Math.PI
// 缩放
mesh.scale.x = 1
mesh.scale.y = 1
mesh.scale.z = 1

MIT Licensed