Why isn't ThreeJS camera.lookAt() working as expected? Am I missing something in my implementation?

When working with Three.js, my goal is to have a camera directed towards a specific point in 3D space.

To achieve this, I attempted to use the camera.lookAt function in the following way:

camera.lookAt(new THREE.Vector3(-100,-100,0));

Unfortunately, it seems like this call has no impact at all. No changes are reflected on the screen regardless of the values I input into the vector.

I recently discovered that by removing the THREE.TrackballControls from my code, the camera.lookAt() function starts working correctly. Could there be an issue with how I'm using THREE.TrackballControls? Here's how I initialize them:

    controls = new THREE.TrackballControls( camera, renderer.domElement );

    controls.rotateSpeed = 10.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.2;

    controls.noZoom = false;
    controls.noPan = false;

    controls.staticMoving = true;
    controls.dynamicDampingFactor = 1.0;

    var radius = 5;
    controls.minDistance = radius * 1.1;
    controls.maxDistance = radius * 100;

    controls.keys = [ 65, 83, 68 ]; // [ rotateKey, zoomKey, panKey ]*/

Subsequently, within my render function, I execute the following:

function render() {
  controls.update();
  renderer.render(scene, camera);
}

Since resources on Three.js documentation are limited, I decided to seek guidance here. Can anyone spot any mistakes in my approach?

Answer №1

After delving into the source code of THREE.TrackballControls, I uncovered a method to direct the camera's view to a specific point by assigning trackballControls.target with the desired THREE.Vector3 coordinates, followed by refreshing the scene.

Answer №2

Caution: I discovered that using both THREE.TrackballControls and THREE.OrbitControls can interfere with the camera.lookAt function. This happens because you pass your camera as a parameter when creating the controls instances. To check if the controls are affecting your camera, try removing them and then using camera.lookAt() or another method to adjust your camera's orientation. It took me some time to figure out why camera.lookAt() wasn't working as expected.

Answer №3

From my perspective, adjusting the original code should be avoided. I have discovered a workaround to accomplish the goal of focusing on a specific point. Once you have defined your "control" variable, simply implement the following two lines of code:

// Assuming you are familiar with setting the camera and myCanvas variables
control = new THREE.OrbitControls(camera, myCanvas);

// Later in your script
control.object.position.set(camX, camY, camZ);
control.target = new THREE.Vector3(targetX, targetY, targetZ);

Remember that this will shift the focus center to your new target. Essentially, your new target will serve as the central point for all camera rotations. It may be challenging to view certain areas since you were used to manipulating the camera based on the default center. Try zooming in as much as possible to understand what I mean. I hope this explanation proves helpful.

Answer №4

After some investigation, I have found a solution. In order to prevent THREE.TrackballControls or THREE.OrbitControls from interfering with camera.lookAt during initialization, you will need to modify the line that defines the control's target property. Instead of using new THREE.Vector3() which defaults to (0, 0, 0), it should be set to the sum of the camera.position vector and the camera.getWorldDirection() vector.

For THREE.TrackballControls, make the following change at line 39:

this.target = new THREE.Vector3().addVectors(/*new line for readability*/
    object.position, object.getWorldDirection());

The same adjustment should also be made for THREE.OrbitControls, specifically on line 36. Although I have not tested this on TrackballControls.js, it has been successfully implemented on OrbitControls.js. I hope this information proves helpful.

Answer №5

An innovative approach is to generate an object (such as a cube) with zero dimensions.

let focalPoint = new THREE.Mesh( new THREE.CubeGeometry(0,0,0));

In the rendering function, adjust the camera's focus towards the position of the focal point.

function updateView() {
    camera.lookAt( focalPoint.position );
    renderer.render( scene, camera );
}

Subsequently, relocate the focal point wherever needed.

Answer №6

Encountering a similar issue, I found a solution using OrbitControls.target. Here's how I tackled it following the controller declaration:

    controller = new THREE.OrbitControls(camera, renderer.domElement);
    controller.addEventListener('change', renderer.domElement);
    controller.target = new THREE.Vector3(0, 1, 0);

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

Declaring types globally in Visual Studio Code for JavaScript programming

My /typings/$app.d.ts file has the following structure: declare class App { test: object } export const $app: App; https://i.sstatic.net/3HW7M.png In order to enable intellisense, I have to auto-import it, resulting in a line like this at the begin ...

Navigate through a given value in the event that the property undergoes a name change with each

Exploring an example found on the JSON site, I am facing a situation where I am using an API with JSON data. The property name "glossary" changes for each request made. For instance, if you search for "glossary", the first property is glossary. However, if ...

I noticed that my regular expression is functioning correctly on regex101, but for some reason, it's

My search works perfectly on regex101 using this link: https://regex101.com/r/z8JCpv/1 However, in my Node script, the third matched group array[2] is returning not only the matching text but also everything following it. An example line from the source ...

The backend function of an aspx page is failing to execute when triggered by a $.ajax request

Currently, I am facing an issue with a web form IndexPage.aspx. The script in this front-end code makes an ajax call to a code-behind function. Take a look at the code snippet below: $.ajax({ type: "POST", url: &apos ...

Fetching basic information from an API using Ember.js

I am facing an issue with my Ember.js page where I am trying to retrieve data from a REST API. The API is provided by apiary.io and it returns a simple set of data as shown below: {"semantics": [ {key : "11111", name : "Block 1"}, {key : "22222", name ...

Tips for effectively utilizing tags in AngularJS search functionality

I attempted to implement a search box that utilizes tags, shown in the image below. Despite trying to use bootstrap tags, it did not work as intended. Here is a visual representation of how the search should be displayed: https://i.sstatic.net/COqai.png ...

Get a file from a distinct internal server than the one where the website is operating

I am trying to download a file from an internal server that is separate from the one where the website is hosted. I have attempted various methods such as... <a href="javascript:Start('file://servername/path/filename.txt')> <a href="// ...

What types of shadowMapTypes are available?

Can you list the potential shadowMapTypes available for renderer? At this time, I am only aware of three: THREE. PCFShadowMap PCFSoftShadowMap PCFBasicShadowMap ...

The collapse feature of Bootstrap 4 Navbar is unresponsive

Struggling with the Bootstrap 4 navbar collapse feature issue. In the mobile viewport, instead of collapsing, it displays items as a vertical list. Here is the code snippet: <html> <body> <!-- Navbar --> <nav class="navbar na ...

Generate div elements dynamically for each object being populated in JSON using JavaScript

I have a main container that displays a list of JSON objects. Each object should be displayed as a separate DIV element with specific details, one after the other. Additionally, I have a comments section on a webpage where the details are stored in JSON f ...

What is the method used by Vue.js to establish observers in computed properties?

Consider this scenario: computed: { greeting() { const state = this.$store.state; if (state.name === 'Joe') { return 'Hey, Joe'; } else { return 'Hello, ' + state.name; } } } Which object(s) w ...

The popover displays the text "[object Object]" when triggered by an ajax event

Upon observing the image, I noticed that my bootstrap popover is triggering and displaying “[object Object]” instead of the database data I retrieved. After adding logs to the JavaScript AJAX code, I can see that the data is being retrieved, but it i ...

What could be causing the issue of PHP not receiving this multidimensional array through Ajax?

Having an issue with receiving a multidimensional array in PHP after posting it from JS using Ajax: $.ajax({ type: 'post', url: 'external_submit.php', dataType: "json", data: { edit_rfid_changes_submit ...

Using jQuery to dynamically add a value to a comment string

Is there a way to dynamically include tomorrow's start and end times in the message for the setupOrderingNotAvailable function if today's end time has passed? The current message states that online ordering will be available again tomorrow from 1 ...

Node.js has the ability to establish internal connections, however it cannot establish connections

I'm having an issue connecting to a JavaScript file on my local server. I'd like to input the external IP address and port in order for it to run externally. This functionality currently works when accessed locally. Below is the code from my serv ...

I encountered a Vue warning indicating an issue in the v-on handler: "Error: Request failed with status code 404"

I recently started learning Vue.js and attempted to follow a tutorial on integrating Axios. Unfortunately, I keep encountering an error that I can't seem to resolve. I initially ran it on localhost:3000, then switched back to 8080, but the issue persi ...

Customizing your buttons in Wordpress with extra CSS styles upon clicking

I am in the process of developing a Wordpress website and I require a button for switching between mobile and desktop versions manually. Within my .css file, I have included: @media (pointer:coarse) {} This adds modifications for the mobile version ...

Troubleshooting: Unable to delete data using $http in AngularJS

When using the $http service in Angular JS to call an API for deleting a message, I am receiving a successful response but the value is not actually being deleted. Interestingly, when I directly access the same API in my browser, the message gets deleted s ...

Troubleshooting issue with Express.json() functionality in the latest release of version 4.17

I'm currently exploring the MEAN stack and I am focused on performing CRUD operations. However, when I send data in the request body from Angular to the server, I end up receiving an empty request body. I'm unsure of where I might be making a mis ...

Tips for updating the date format in Material UI components and input fields

Is there a way to customize the date format in Material UI for input text fields? I am struggling to format a textField with type 'date' to display as 'DD/MM/YYYY'. The available options for formatting seem limited. It would be helpful ...