Moving objects with Three.JS

Seems like I might just be overlooking a simple solution here. I have a setup with a spotlight pointing backward from the camera towards a plane geometry, as well as some randomly scattered boxes. My goal is to create a basic top-down demo. I move the camera using the WASD keys, capturing the position, resetting the Y to zero, and then making the camera focus on that position. I also adjust the light's target to match the camera's new position. The camera moves smoothly, but it seems like the light isn't changing its focus, at least as far as I can tell.

Here's how I create the light and its target:

this.playerLight = new THREE.SpotLight(0xffffff);
this.playerLight.castShadow = true;
this.playerLight.position.set(0, 40, 0);
this.spotlightTarget = new THREE.Object3D();
this.spotlightTarget.position.set(0, 0, 0);
this.playerLight.target = this.spotlightTarget;
this.playerLight.shadowCameraVisible = true;
this.scene.add(this.playerLight);

Next, here's my keyboard event handling code:

window.addEventListener("keydown", function (e) {
  var moved = false;
  switch ( event.keyCode ) {
    case 87: // W
      e.preventDefault();
      _this.camera.position.x -= 0.2;
      moved = true;
      break;
    case 65: // A
      e.preventDefault();
      _this.camera.position.z += 0.2;
      moved = true;
      break;
    case 83: // S
      e.preventDefault();
      _this.camera.position.x += 0.2;
      moved = true;
      break;
    case 68: // D
      e.preventDefault();
      _this.camera.position.z -= 0.2;
      moved = true;
      break;
    default:
      return true;
  }

  if (moved) {
    var lookAtPos = _this.camera.position.clone();
    lookAtPos.y = 0;
    _this.camera.lookAt(lookAtPos);
    _this.playerLight.position.x = lookAtPos.x;
    _this.playerLight.position.z = lookAtPos.z;
    _this.spotlightTarget.position.set(lookAtPos.x, lookAtPos.y, lookAtPos.z);
  }
}, false);

Any thoughts on what might be causing this issue?

Answer №1

The translation of your spotlight target has been successfully completed, however, the spotlight itself is not following the target as expected.

In three.js r.69, the Spotlight.target property exists within the light, but it is not integrated into the scene graph, causing target.matrix and target.matrixWorld to not update accordingly.

To resolve this issue, one solution is to include spotlight.target in the scene. Alternatively, you can assign an object that already exists in your scene as the target:

spotLight.target = myObject;

three.js r.69

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

Using d3.js to dynamically change the color of svg elements based on their data values

I was searching for a way to dynamically color SVG rectangles based on values from a dataset. If I were to create rectangles for each data entry, how could I adjust the rectangle's color according to the data value? Here is what I currently have: // ...

Creating dropdown menus dynamically and populating them based on the selection made in one dropdown menu to determine the options available

Looking to enhance the filtering options in my ngGrid, I stumbled upon the concept of Filtering in Ignite UI grid and was impressed by its functionality. I am now attempting to implement a similar feature in AngularJS. Breaking down the task into 4 compon ...

Is there a way to transform an HTMLCollection into an array without depleting it of its elements?

I've been attempting to transform a collection of 4 divs in HTML into an array, but all my efforts seem to lead to the array becoming void. <div class="container"> <div class="shape" id="one"></div> <div class="sh ...

Creating an interactive checkbox input field utilizing a JSON-driven database

Can someone assist me with creating dynamic checkboxes? I have JSON data structured as follows: [ { "categoryName": "Category 1", "items": [ { "value": "value1", "label": "label1" }, { "value": "value2" ...

Creating a collection by gathering data from interactive fields with the help of AngularJS

I have a project to create an attendance system for employees. The system requires me to track the attendance status of each employee by generating a dynamic form with text input fields and checkboxes using angularjs ng-repeat inside a table. This form wil ...

When the page is scrolled, trigger a click event on the next button in

Currently, I have a listing page that features pagination at the bottom. However, my goal is to transform this into an infinite loading page. The issue I am facing is that when the click event triggers after scrolling to the bottom, it makes calls for pag ...

The display of 'App' seems to be experiencing issues within the render method

Can someone help me with this issue? I am encountering the following error: Uncaught Error: Invariant Violation: Element type is invalid - expected a string for built-in components or a class/function for composite components, but received an object. Bel ...

Oops! There was a validation error as the duration was not formatted as a number. Please make sure to provide a valid numerical value for the duration field

When attempting to update data from a MongoDB database and checking the results on Postman, an error is encountered. The error reads as follows: "Error: ValidationError: duration: Cast to Number failed for value \"NaN\" at path \"duration&bs ...

Is there a way to pass a v-modal as an array when setting Axios params?

I am currently dealing with a Vue Multiselect setup where the v-model is an array to accommodate multiple selected options. The challenge I am facing involves calling a route within the loadExtraOptions method and passing the array of IDs as a parameter ...

Having trouble with npm install, unable to successfully install any node modules after cloning my project from git

I recently pulled my project from a git repository and encountered issues while attempting to run npm install. Despite trying different solutions like running npm install --save core-js@^3 to address the core-js error, I keep receiving the same message pr ...

Why is my React component not updating after changing the state using Set State?

Uncovering the elusive problem seems impossible. Despite state changes, the component remains unrerendered. Here's the code: export const InterestsPupup: React.FC = ({interests, title, buttonText}) => { const [activeItems, setActiveItems] = useSt ...

Python-JavaScript Integration Problem

I'm a beginner when it comes to Javascript, Python, and PHP. In my Javascript program, I have a button that triggers a Python script and displays the returned value on the screen. My goal is to steer clear of using Jquery and Json. Here are the snipp ...

Efficiently converting arrays to strings in JavaScript using mapping techniques

My goal is to retrieve data through AJAX without formatting it as JSON, so I took the initiative to encode it myself. The data I am working with consists of client records: where the pound sign (#) separates the client records, the pipe sign (|) separates ...

Guide to generating a text string by utilizing the foreach loop

Is there a way to combine text strings from interfaces into a single file for display in UI? The current code is generating separate files for each interface. How can I achieve the expected result of having all interfaces in one file? Additionally, is it ...

Executing a Jquery click event after a delay with setTimeout

I am working with an <a> element that, when clicked, triggers a handler like this: function onCummReportClick(e) { if ($(e.currentTarget).attr('href').indexOf('csv') !== -1) { { return true; } //Here s ...

Always keep your phone in landscape orientation for optimal website viewing

Currently, I am facing an issue with my website where it functions perfectly on mobile devices in landscape orientation but elements get distorted when viewed in portrait mode. Is there a method to ensure that the website is always displayed in landscape ...

In what way can the button display the permission directly on the page?

When the website notification is granted, a green button should be displayed. If it is denied, show a red button instead. The button comes with a CSS style and a checkbox but does not have the permission to grant or allow any permissions on the page. Butt ...

Creating multi-dimensional arrays using array lists with Axios and Vue.js

My knowledge of axios and JavaScript is limited, and I find myself struggling with creating a multi-dimensional array. 1. This is how I want my data to be structured : https://i.stack.imgur.com/kboNU.png userList: [ { ...

Using AngularJS, learn how to populate array objects within a JSON object

I'm trying to load array objects from a multi-select control, then populate a model object called "name" with its name and age values. After that, I want to load an array from a select element into the model object. However, the ng-model directive on ...

In need of styling text using CSS?

Despite setting the CSS to .text { word-wrap : break-word; max-width: 100px}, the text is not wrapping as expected. It is still displaying in a single line. I am anticipating that the large text should wrap onto the next lines. ...