【发布时间】:2021-10-10 02:13:59
【问题描述】:
我打算使用 Orbit Control 来做一个简单的第三人称视角, 但我似乎无法弄清楚该怎么做。 当我围绕一个物体旋转相机,然后按说“W”键向前移动时,我希望物体“看”逐渐旋转并移动到相机面对的新方向。 我该怎么做?
【问题讨论】:
标签: three.js
我打算使用 Orbit Control 来做一个简单的第三人称视角, 但我似乎无法弄清楚该怎么做。 当我围绕一个物体旋转相机,然后按说“W”键向前移动时,我希望物体“看”逐渐旋转并移动到相机面对的新方向。 我该怎么做?
【问题讨论】:
标签: three.js
可以通过逐渐将对象旋转到相机方向来做到这一点。
为简单起见,在此处制作了一个代码笔,它使用通用替换轨道控件:
https://codepen.io/cdeep/pen/QWMWyYW
// Get the X-Z plane in which camera is looking to move the player
camera.getWorldDirection(tempCameraVector);
const cameraDirection = tempCameraVector.setY(0).normalize();
// Get the X-Z plane in which player is looking to compare with camera
model.getWorldDirection(tempModelVector);
const playerDirection = tempModelVector.setY(0).normalize();
// Get the angle to x-axis. z component is used to compare if the angle is clockwise or anticlockwise since angleTo returns a positive value
const cameraAngle = cameraDirection.angleTo(xAxis) * (cameraDirection.z > 0 ? 1 : -1);
const playerAngle = playerDirection.angleTo(xAxis) * (playerDirection.z > 0 ? 1 : -1);
// Get the angle to rotate the player to face the camera. Clockwise positive
const angleToRotate = playerAngle - cameraAngle;
// Get the shortest angle from clockwise angle to ensure the player always rotates the shortest angle
let sanitisedAngle = angleToRotate;
if(angleToRotate > Math.PI) {
sanitisedAngle = angleToRotate - 2 * Math.PI
}
if(angleToRotate < -Math.PI) {
sanitisedAngle = angleToRotate + 2 * Math.PI
}
// Rotate the model by a tiny value towards the camera direction
model.rotateY(
Math.max(-0.05, Math.min(sanitisedAngle, 0.05))
);
【讨论】: