As a newcomer to THREE.js, I decided to create a Mini Game for learning JavaScript and THREE.js. In this game, players can explore space and various space objects (still a work in progress).
One issue I encountered is that when the scene and objects are rendered, and the player starts moving their cuboid, the camera doesn't move along with it. Instead, it only rotates in place while looking at the player's object without moving away from the world origin.
Below is the code snippet:
import './style.css'
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
// Scene object
const scene = new THREE.Scene();
const clock = new THREE.Clock();
var cameraObject, keys;
// other variables...
My goal is to implement a Third Person Camera that follows the cuboid and rotates along with the object on the screen.
First attempt:
const idealOffset = new THREE.Vector3(0, 0, -80);
function animate(){
...
perspectiveCamera.position.set(0, 0, -80);
perspectiveCamera.applyQuaternion(cube.rotation);
perspectiveCamera.position.add(cube.position);
perspectiveCamera.lookAt(idealOffset);
...
}
While the camera initially moves with the cube, it eventually returns to look at the world origin.
Second attempt:
// Animate objects
requestAnimationFrame( function animate(milliseconds) {
const delta = clock.getDelta();
let moveDistance = 10*delta;
let rotateAngle = Math.PI/2*delta;
requestAnimationFrame( animate );
// other code...
Although the camera now follows the cube, it becomes upside-down when the cube is rotated 180 degrees on the x-axis, and it moves rigidly with the player.
This challenge led me to delve into topics like rotating and translating in 3D space, Euler angles, quaternions, and gimbal lock. I am seeking guidance on how to incorporate quaternions into my project.
Any assistance, references, or suggestions would be greatly appreciated.
Thank you in advance.