I am currently experimenting with a point-and-click navigation feature in three.js for a project. The goal is to move the camera to the location where the user clicks on the screen using a raycaster along with a simple mechanic implemented with gsap:
const move_cam = () => {
const new_pos = { ...marker.position };
gsap.to(camera.position, {
duration: 2,
x: new_pos.x,
z: new_pos.z,
onComplete: () => {
}
});
};
However, I encountered an issue when using OrbitControls alongside this mechanic, as the camera would always orient towards a specific target while moving:
The reason behind this behavior lies in how OrbitControls functions by assigning a fixed target for the camera.
Several strategies were attempted to address this challenge, including disabling and re-enabling OrbitControls during camera movement or preventing OrbitControls from affecting the camera's target. However, these solutions proved ineffective in maintaining the desired camera orientation throughout the animation.
As a final approach, I devised a method that involved storing the distance between the camera and its target in a variable named "offset", which was then used to set a new target at the end of the animation. This revised version of the move_cam()
function aimed to resolve the issue:
const move_cam = () => {
camera_is_moving = true;
const offset = {
x: controls.target.x - camera.position.x,
y: controls.target.y - camera.position.y,
z: controls.target.z - camera.position.z,
};
const new_pos = { ...marker.position };
new_pos.y = CAMERA_HEIGHT;
gsap.to(camera.position, {
duration: 2,
x: new_pos.x,
y: new_pos.y,
z: new_pos.z,
onComplete: () => {
controls.target.x = offset.x + camera.position.x;
controls.target.z = offset.x + camera.position.z;
offset.x = controls.target.x - camera.position.x;
offset.y = controls.target.y - camera.position.y;
offset.z = controls.target.z - camera.position.z;
camera_is_moving = false;
}
});
};
Despite implementing this solution, a slight twitch in the camera's movement was still observed at the end of the animation, indicating a discrepancy in setting the new target position. Further investigation is required to determine the root cause of this issue and ensure consistent camera rotation before and after the animation.
If anyone has insights or suggestions on how to improve this functionality, your assistance would be greatly appreciated. Feel free to explore the project on Github repo to gain a better understanding of the problem. The complete JavaScript file can be found here.
Thank you for your support and input in advance.