TrackballControls causing incorrect camera alignment in three.js when moving light

My goal is to adjust the lighting in my camera setup. I have implemented the following code:

  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(40, windowWidth / windowHeight, 1, 10000);
  camera.position.z = 50;
  scene.add(camera);


  var dirLight = new THREE.DirectionalLight(0xffffff);
  **dirLight.position = camera.position;**
  dirLight.position.normalize();
  scene.add(dirLight);

  renderer = new THREE.WebGLRenderer();
  renderer.setSize(windowWidth, windowHeight);
  i_container.appendChild(renderer.domElement);

  controls = new THREE.TrackballControls(camera);

  controls.rotateSpeed = 1.0;
  controls.zoomSpeed = 1.2;
  controls.panSpeed = 0.8;

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

  controls.staticMoving = true;
  controls.dynamicDampingFactor = 0.3;

  controls.keys = [65, 83, 68];

  controls.addEventListener('change', render);

Everything seems to be functioning properly: the light moves with the camera. However, I am encountering an issue where the camera initializes within my object, requiring me to zoom out to view the entire object.

Interestingly, when I remove the line - "dirLight.position = camera.position;", the scene initializes correctly and I can see the entire object.

I would greatly appreciate it if you could provide some insight into what might be causing this issue. I have not altered the camera's position, so why do I find myself inside the object?

Thank you, Zhenya

Answer №1

Forget about TrackballControls. The issue lies within the following code:

dirLight.position = camera.position;
dirLight.position.normalize();

The problem is that the camera position is being normalized.

You can safely remove dirLight.position.normalize(); it serves no purpose at this point.

Personally, I would opt for using a pointLight instead. However, your current approach does function with the latest version of three.js.

three.js r.58

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

JavaScript: Obtaining the month based on the week number and year

Can someone assist me in determining the month based on a given week number and year? For example: Week - 48 Year - 2023 Desired Output - 11 ...

What is the solution to the problem "How can you resolve the issue where 'Cannot set property 'ref' of undefined' occurs"?

My goal is quite simple - I just want to retrieve data from Cloud Firestore. Below is the code snippet I am using: import React from 'react'; import firebase from "react-native-firebase"; export default class newsFeed extends React.Component { ...

JavaScript framework that is easily customizable to include support for XmlHttpRequest.onprogress, even if it needs to be emulated

Which JavaScript library or framework offers support for the "onprogress" event for XmlHttpRequest, even if it needs to be emulated using a plugin or extension? Alternatively, which JavaScript framework is the most straightforward to extend in order to add ...

Enhance CKEditor with Linked Select Boxes Plugin

I have ventured into writing a CKEditor Plugin and have grasped the basic concepts. For instance: CKEDITOR.dialog.add( 'addDocumentGroupDialog', function ( editor ) { return { title: 'Link to a document group', min ...

Is it possible to incorporate HTML and CSS into a npm package?

I've been searching extensively for an answer to this question, but haven't found a clear answer. I recently began using the node package manager and I'm wondering if it's possible to publish a package that includes HTML and CSS, or if ...

JavaScript Tutorial: Merging Two Arrays while Maintaining Original Index Positions

I have two arrays that I need to merge together. One array contains numbers, while the other array contains the corresponding titles for those numbers. This data was retrieved from a csv file, hence the current structure of the arrays. Array 1: dataResul ...

Incorporate content from a single HTML file into a different one

Hello, I am working with two HTML documents - let's call them index.html and index2.html for this example. I am looking to embed all the code within the body tag of index2.html into a section within index.html. Is there a way to create this connectio ...

The screen-responsive navigation bar is experiencing functionality issues

I am facing an issue with my navigation bar on both desktop and mobile. When I maximize the window while the mobile navbar is open, it disappears as expected but the desktop navbar does not appear. I am using a bootstrap template and I am unsure if solving ...

When implementing dynamic routing in Next.js, an error occurs with TypeError: the 'id' parameter must be a string type. It is currently

I’m encountering a problem while creating dynamic pages in Next.js. I'm fetching data from Sanity and I believe my code is correct, but every time I attempt to load the page, I receive a type error - “the ‘id’ argument must be of type string. ...

"Addressing the issue of ineffective form validation for empty or whitespace inputs

I've been working on creating a form and everything seems to be going well except for the validation aspect. It doesn't highlight when intentionally left blank or filled with spaces. I have included "required" in the HTML which partially achieves ...

What is the proper way to handle a 504 response header in an AJAX request using jQuery?

Recently, I encountered an issue with an AJAX call from the client that caught my attention. Here is a snapshot of how it looked: $.ajax({ 'url': '/converter/ajax-make-corrections/', 'data': { ...

Creating HTML Divs with Equal Heights

I have written this JavaScript code, but I feel like there might be some redundancy. Does anyone have suggestions on how to improve and optimize this code? var boxHeights = []; $('.box').each(function() { boxHeights.push( $(this).outerHeight ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

Unexpected 404 Error in Node.JS Express following a POST submission

I've recently built my first application using Express and MySQL. I'm encountering an issue with saving data in my database - every time I make POST requests, I receive a status 404 error and nothing beyond that. This roadblock is preventing me f ...

If the JSON file exists, load it and add new data without recreating the file or overwriting existing data

Currently, I am in the process of developing a function called createOrLoadJSON(). This function is responsible for checking whether an existing JSON file exists within the application. If the file does not exist, it should create a new file named "userDat ...

Converting a JSON format with JavaScript

As the data for a simple online store is extracted from a headless CMS, it is structured in the following format: [ { "id": 12312, "storeName": "Store1", "googleMapsUrl": "https://example1.com", "country": "Australia", ...

Calculating Time Difference in JavaScript Without Utilizing moment.js Library

I have two timestamps that I need to calculate the difference for. var startTimestamp = 1488021704531; var endTimestamp = 1488022516572; I am looking to find the time difference between these two timestamps in hours and minutes using JavaScript, without ...

The ExtJs 4 MultiSelect Edit Form is experiencing issues with loading selections

I am seeking assistance with implementing a combo box with multiple select in Extjs 4. I am looking to use this feature in my forms to handle a simple ManyToMany relationship split by a central table: User -< User_Group >- Group. Where: User: id, ...

What is the method for determining the height of a div element when it is set to 'height=auto'?

I am trying to determine the height of a specific div using Javascript. Here is the script I have written: function getMainDivHeight() { var num = document.getElementById('up_container').style.height; return num; } However, this script ...

Saving an "Online User Registry" for a messaging platform (PHP/AJAX)

In my setup, I manage multiple chat rooms by storing the list of chat users in a PHP variable. As users join or leave a room, their names are added to or removed from this list. To ensure data persistence, I rely on memcached. Periodical AJAX requests are ...