I'm struggling to make the Perspective Camera track the player's movement. The Camera seems glued to the World origin

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.

Answer №1

To easily track an object using OrbitControls, all you need to do is update the .target property with the position of the desired object. By doing so, the camera will smoothly follow the object's movement. For a detailed explanation, refer to the documentation here:

orbitControls.target = cube.position;

The line

cameraObject.add(perspectiveCamera);
seems unnecessary unless you intend to modify the cameraObject later on.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with mouseover in the jQuery area

As I navigate through a WordPress website, I am attempting to create a mandala using dynamic images. Utilizing jQuery and CSS areas, I aim to display the corresponding image when hovering over a specific section. However, I am facing an issue where there ...

The conditional statement for ajax is malfunctioning

I am encountering an issue with some ajax coding. The if condition is not working as expected - whenever the program runs, only the else statement gets executed even when the if statement should be satisfied. <script type="text/javascript> funct ...

How do I disable the hover and click highlighting effect on a div in Vuetify using v-on in Vue2?

Currently, I have implemented a Vuetify VListItem in a NavigationDrawer with an on click listener that displays a menu in the div below. The menu is functioning properly - opening and closing as expected. However, it highlights on hover/click which I wou ...

Using Slick.JS to Sync Navigation with Main Slider, Automatically Resetting to First Slide

I have a question about the functionality of the Slick.JS plugin that I'm using. In my project, I have two carousels with five slides each. The top carousel displays one slide at a time, while the bottom carousel shows all five slides concurrently. My ...

a guide on retrieving FormData objects in PHP

Hey everyone, I have a question regarding a sample code snippet I posted here. In this code, I am successfully uploading a file using Ajax JQuery. However, I am struggling to figure out how to read the content of the uploaded file in my PHP code. Can anyon ...

Attempting to configure Kafka consumer and producer components

Trying to establish a basic producer-consumer flow with Kafka, utilizing node-rdkafka Operating in debug: 'all' mode, the logs display: Producer: test [0]: MessageSet with 1 message(s) delivered Consumer: Fetch topic test [0] at offset 38 (v2) ...

personalizing material-ui component styles – set select component color to be pure white

I am looking to implement a dropdown menu using material-ui components (refer to https://material-ui.com/components/selects/). To do so, I have extracted the specific component from the example: Component return <div> <FormControl variant="outli ...

Issue with envMap when using tCube as uniforms in Three.js r111 ShaderLib.cube

I am currently working on creating a 360 panorama viewer using AFrame, and I have developed a custom component to utilize a cubemap for the sky. The process involves loading a texture with the 6 cube faces using THREE.CubeTextureLoader, followed by execut ...

Navigate to the top of the page prior to updating the Link route in NextJS

Whenever I click on a link to navigate to a new page, the page loads and immediately scrolls to the top. I want to change this behavior so that the scroll resets to the top before the new page is rendered. You can observe this issue on . If you scroll do ...

Leveraging the power of jQuery and vanilla JavaScript to create a pop-up print window for a Div element within a CMS platform that does not support media query stylesheets

I have been grappling with this particular issue for weeks now, seeking guidance from previous inquiries here. Yet, despite the helpful hints, I am still struggling to find a viable solution. My website features a scrolling sidebar measuring approximately ...

The custom service is failing to load, in the simplest terms possible

After creating a dataService.j that contains the following: angular.module('dataService', []) .service('gameDataService', function() { var _gameData = { loggedIn: "false", gameJoined:"false", tableFu ...

Storing a photo taken with a camera to a local directory on the computer

Currently, I am utilizing HTML5 inputs to capture a picture from the camera by using the code below: <input id="cameraInput" type="file" accept="image/*;capture=camera"></input> Subsequently, I am obtaining the image in blob format and manip ...

how to change the color of a specific item in a list created using v-for

I'm a beginner when it comes to vueJs and I'm attempting to toggle the class "active" on a single element once it has been clicked. Currently, my code toggles all elements with the class material_icons. How can I modify it to toggle only the elem ...

unable to access POST information

I have encountered an issue with getting a basic AJAX POST to function properly. After facing difficulties with using a jQuery .click, I switched to an onclick method. I am unsure if I am making a glaring mistake or if there could be an issue with Apache s ...

Multiple executions of Google API sign in listener

I have been working on a Vue module that allows users to add events to Google Calendar easily. Once a user signs in, there is a listener in place to call a method for adding an event to the calendar. To access the gapi functionalities required for this tas ...

Check out the new Bootstrap 5 form when it's successfully validated

I need to execute some JavaScript if my form is valid. I am using Bootstrap 5 and found this code, but I am unsure how to add 'if form.is_valid {}' <script> (function () { 'use strict' const forms = document.querySelectorAll(&apos ...

A guide on calculating the number of days between two dates using Angular 12

I am currently utilizing Angular 12 for my project. The calculation of days based on two dates seems to be working perfectly fine in Chrome, but unfortunately, it fails in Firefox. In my TypeScript file: getDaysCount(firstDate: any, secondDate: any) { ...

Managing errors in Node.js when inserting data into MongoDB

Hello everyone, I'm currently working on handling errors in the user signup module using Express. However, I'm facing an issue where the errors are not being handled correctly. Here is my code: handler.post(async (req, res) => { let otp = M ...

What sets xhr.response apart from xhr.responseText in XMLHttpRequest?

Is there any difference between the values returned by xhr.response and xhr.responseText in a 'GET' request? ...

The div is set to a position of absolute, causing the overflow-y property to be set to auto. As a

I am facing an issue with a div that has absolute positioning nested inside other divs. If you take a look at the code snippet below from http://jsfiddle.net/d8GYk/, you'll notice the styling properties applied to the div. <div style="position: ...