I want to make the camera able to orbit around the character, as well as follow the character as it walks. It can follow the character, but it locks up the rotation for the mouse. Everytime I try to use the mouse to orbit around the character, it snaps back to where the camera is set and looking at, making it unable to rotate.
//#region CAMERA
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(7, 20, -13)
// camera.rotateX(0.1 * Math.PI)
// camera.rotateY(1 * Math.PI)
// camera.rotateZ(0 * Math.PI)
const controls = new OrbitControls(camera, renderer.domElement);
controls.autoRotate = false;
controls.enablePan = false;
controls.minPolarAngle = Math.PI / 4; // 45 degrees
controls.maxPolarAngle = Math.PI * 1.5 / 4; // 135 degrees
// camera.position.set(0, 300, 0);
// const orbit = new OrbitControls(camera, renderer.domElement)
const cameraOrigin = new THREE.Vector3(0, 1.5, 0);
camera.lookAt(cameraOrigin);
controls.update();
//#endregion
//#region CHARACTERS
var xSpeed = 0.1; // Adjust the speed as needed
var ySpeed = 0.1; // Adjust the speed as needed
var keys = {}; // Object to track pressed keys
var cameraOffset = new THREE.Vector3(7, 20, -13);
gltf.load(character3.href, function (gltf) {
const model = gltf.scene;
scene.add(model);
model.position.set(0, 0, 0)
model.scale.set(10, 10, 10)
const clips = gltf.animations;
mixer = new THREE.AnimationMixer(model);
const idleClip = THREE.AnimationClip.findByName(clips, 'Idle');
const idleAction = mixer.clipAction(idleClip);
idleAction.play();
const walkClip = THREE.AnimationClip.findByName(clips, 'Run_Gun');
const walkAction = mixer.clipAction(walkClip);
// Event listeners for keydown and keyup events
document.addEventListener("keydown", (event) => {
keys[event.keyCode] = true;
});
document.addEventListener("keyup", (event) => {
delete keys[event.keyCode];
walkAction.stop();
});
// Animation loop to handle smooth movement
function animate() {
requestAnimationFrame(animate);
// Update model position based on pressed keys
if (keys[87]) { // W key
model.position.z += ySpeed;
walkAction.play();
}
if (keys[83]) { // S key
model.position.z -= ySpeed;
walkAction.play();
}
if (keys[65]) { // A key
model.position.x += xSpeed;
walkAction.play();
}
if (keys[68]) { // D key
model.position.x -= xSpeed;
walkAction.play();
}
if (camera && model) {
camera.position.copy(model.position).add(cameraOffset);
controls.target.copy(model.position);
// camera.lookAt(model.position);W
}
// Update animation mixer
// if (mixer) {
// mixer.update(delta);
// }
}
animate(); // Start the animation loop
});
//#endregion
function animate() {
// requestAnimationFrame(animate);
var delta = clock.getDelta();
if (mixer) mixer.update(delta);
renderer.render(scene, camera)
}
renderer.setAnimationLoop(animate);