当物体在旋转组内时如何将其放置在镜头前?

How to place an object in front of camera when it is inside a rotated group?

在任意点移动对象时,如何考虑父对象的变换?我这样做 this.cube.position.copy(this.camera.position)

class Sketch {
  constructor() {
    this.bind()
    this.renderer()
    this.camera()
    this.scene()
    this.objects()
    this.resize()
    this.listen()
  }

  bind() {
    this.render = this.render.bind(this)
    this.resize = this.resize.bind(this)
    this.moveObject = this.moveObject.bind(this)
  }

  renderer() {
    this.renderer = new THREE.WebGLRenderer()
    document.body.appendChild(this.renderer.domElement)
  }

  camera() {
    this.camera = new THREE.PerspectiveCamera(0, 0, 0.1, 2000)
    this.camera.position.z = 1000
  }

  scene() {
    this.scene = new THREE.Scene()
  }

  objects() {
    this.group = new THREE.Group()
    this.group.rotation.y = Math.PI / 4
    this.group.position.z = -1000

    const geometry = new THREE.BoxGeometry(1, 1, 1)
    const material = new THREE.MeshBasicMaterial()
    this.cube = new THREE.Mesh(geometry, material)

    this.group.add(this.cube)
    this.scene.add(this.group)
  }

  moveObject() {
    this.cube.position.copy(this.camera.position)
  }

  resize() {
    this.renderer.setSize(innerWidth, innerHeight)
    this.renderer.setPixelRatio(Math.min(devicePixelRatio, 2))
    this.camera.aspect = innerWidth / innerHeight
    this.camera.fov = 2 * Math.atan((innerHeight / 2) / 1000) * (180 / Math.PI)
    this.camera.updateProjectionMatrix()
    this.cube.scale.set(150, 150, 150)
  }

  listen() {
    addEventListener('resize', this.resize)
    addEventListener('click', this.moveObject)
    requestAnimationFrame(this.render)
  }

  render(t) {
    requestAnimationFrame(this.render)
    this.renderer.render(this.scene, this.camera)
  }
}

new Sketch()
body {
  margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>

因为相机在世界space,你可以简单地将它的位置转换成组的本地space。

this.cube.position.copy( this.camera.position ); // copies the WORLD position
this.group.worldToLocal( this.cube.position ); // position now in GROUP space

Object3D.worldToLocal 函数将 Vector3 从世界坐标系(相机所在的位置)转换为调用者的坐标系(在本例中为 this.group)。因此,即使您最初将世界位置复制到 this.cube,它也会在下一行转换回组的局部坐标系。