Hello, I have a problem with rotating the camera.
I want the camera to rotate on the left 90° slowly when I press the left key one time.
When i press left key, the camera rotate 90° on the left but it’s instantly, i want the camera to rotate 90° slowly. if (moveLeft) { camera.rotation.y += (Math.PI / 2); }
After, I put a parameter for time (delta) trying to resolve the problem, but when i press the key one time it rotate slowly but not 90° (very lower):
function animate() { render(); requestAnimationFrame(animate); var delta = clock.getDelta(); animatePlayer(delta); }
function animatePlayer(delta) {
if (moveLeft) {
camera.rotation.y += (Math.PI / 2)*delta; }}
On the right track. If you want the animation to take a specific amount of time I would suggest the following:
var start = 0;
var goal = 0;
var timer = 0;
function animate() {
render();
var delta = clock.getDelta();
animatePlayer(delta);
requestAnimationFrame(animate);
}
function animatePlayer(delta) {
if (timer < 1.0) {
timer += delta; // Increase the timer value
//Use interpolation to move from the start towards the goal, by 'timer' percentage;
camera.rotation.y = THREE.Math.lerp(start, goal, timer);
}
}
// Can set this however you want, but the idea is to store the start, goal and reset the timer.
window.addEventListener('keydown', function(key){
timer = 0;
start = camera.rotation.y;
goal = start + Math.PI/2;
});
This method doesn’t scale well, so will need to add more states for if you wanted to rotate right/up/down etc. A way of doing this is creating a state machine structure, where you store the state (‘rotatingRight’/‘rotatingLeft’) and use a function to set the states. A state can only be set to ‘rotate’ if it is currently at ‘idle’, and goes to ‘idle’ once animation is complete. Further reading