Three.js smooth rotation in character control

Code :

I’ve written a code that adds character movement to an Object3D in Three.js
WASD respectively sets the move forward , left , backward , right variables

  • constants :
walkinbgSpeed = 5;
rotationSpeed = Math.PI ;
  • updateRAF : passed deltatime in seconds , updates movement position then calls rotate
 updateRAF(dts) {
        if (this.moveForward) {
            this.model.position.z += this.walkinbgSpeed * dts;
            this.rotate(dts, 0)
        }
        if (this.moveBackward) {
            this.model.position.z -= this.walkinbgSpeed * dts;
            this.rotate(dts, Math.PI)
        }
        if (this.moveLeft) {
            this.model.position.x += this.walkinbgSpeed * dts;
            this.rotate(dts, Math.PI/2)
        }
        if (this.moveRight) {
            this.model.position.x -= this.walkinbgSpeed * dts;
            this.rotate(dts, -Math.PI/2)
        }

    }
  • rotate : smoothly rotates an Object3D by gradually increments the interpolation factor t + using the quaternion slep function directly on the model’s quaternion
 rotate(dts, angle) {
        let t = 0;

        const animateRotation = () => {
            t += this.rotationSpeed * dts;

            if (t >= 1) {
                t = 1; // Clamp t to ensure it doesn't exceed 1
            }

            const qb = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);

            this.model.quaternion.slerp(qb, t);

            if (t < 1) {
                requestAnimationFrame(animateRotation); // Continue animation if not finished
            }
        };

        requestAnimationFrame(animateRotation);
    }

Problem :

  • Pressing one direction at a time rotates the model smoothly as intended

  • Combining two direction buttons starts with a smooth rotation , ends up insta-rotating the model in the last held button direction with no smoothness applied

Note :

  • If needed full code can be provided

  • Any help is greatly appreciated