当我单击一个对象时,我可以围绕它移动和旋转。
这是不平滑的代码:
mouseEvents() {
window.addEventListener('click', (event: MouseEvent) => {
event.preventDefault()
// Get the mouse position
this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1
this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1
this.raycaster.setFromCamera(this.mouse, this.camera)
var intersects = this.raycaster.intersectObjects(this.scene.children, true)
for (var i=0; i<intersects.length; i++) {
// Look at the object and rotate around it
this.controls.target.set( intersects[i].point.x, intersects[i].point.y, intersects[i].point.z )
// Move to the object
this.camera.position.x = intersects[i].point.x
this.camera.position.y = intersects[i].point.y
this.camera.position.z = (intersects[i].point.z) + 1000
}
})
}
现在,我想做完全相同的铰接,但旋转并平滑移动。在互联网上阅读了一堆之后,我找到了TweenJS并使用了它。问题是我可以平稳地移向物体,但我不知道如何看待物体并绕其平稳旋转。
这是简单的代码:
mouseEvents() {
window.addEventListener('click', (event: MouseEvent) => {
event.preventDefault()
// Get the mouse position
this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1
this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1
this.raycaster.setFromCamera(this.mouse, this.camera)
var intersects = this.raycaster.intersectObjects(this.scene.children, true)
for (var i=0; i<intersects.length; i++) {
// Look at the object and rotate around it smoothly (using tweenjs I suppose)
????????????
// Move to the object smoothly
var position = this.camera.position;
var target = { x : intersects[i].point.x, y: intersects[i].point.y, z: intersects[i].point.z + 1000 };
var tween = new TWEEN.Tween(position).to(target, 2000);
tween.easing(TWEEN.Easing.Linear.None)
tween.start()
}
})
}
您可能需要在渲染循环或补间自定义更新功能中的某处添加camera.lookAt(yourTargetPoint)。
var target = new THREE.Vector3()
mouseEvents() {
window.addEventListener('click', (event: MouseEvent) => {
event.preventDefault()
// Get the mouse position
this.mouse.x = (event.clientX / window.innerWidth) * 2 - 1
this.mouse.y = -(event.clientY / window.innerHeight) * 2 + 1
this.raycaster.setFromCamera(this.mouse, this.camera)
var intersects = this.raycaster.intersectObjects(this.scene.children, true)
for (var i=0; i<intersects.length; i++) {
target.copy(intersects[i].point)
var tween = new TWEEN.Tween(this.camera.position).to(target, 2000)
tween.easing(TWEEN.Easing.Linear.None)
tween.onUpdate(() => {
this.camera.lookAt( target )
})
tween.start()
break; // BREAK HERE BECAUSE WE ONLY CARE ABOUT THE FIRST/AKA NEAREST COLLISION
}
})
}
您还需要确保将相机添加到场景中。您可以使用ISNT附加到场景的摄像机进行渲染,但是在渲染阶段不会更新其矩阵,在这种情况下,您必须调用.updateMatrixWorld()来强制更新其矩阵。但是它更容易为scene.add(camera)
当我这样做时,出现“无法读取未定义的属性'lookAt'”,您知道为什么吗?
this.camera.lookAt?
好的,我不再有此错误,并且onUpdate()使一切烦恼,但这一点都不顺利。相机正在平稳地朝着物体移动,并在最后一秒旋转并看着物体
您必须在调用controls.update之后执行.lookAt,以便它将覆盖controls.updates lookAt(controls.target)或删除对controls.update的调用。
我用当前版本的代码编辑了帖子,可以编辑吗,这样我就能理解您的意思了,因为我必须承认我听不懂:s