How come the light position is not updating?

I am currently using the three.js library to create an animated cylinder:

let renderer, camera, scene, light, cylinder;

initialize();
animate();

function initialize() {
  renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight);

  scene = new THREE.Scene();

  light = new THREE.SpotLight();
  scene.add(light);

  cylinder = new THREE.Mesh();
  cylinder.material = new THREE.MeshToonMaterial({ color: "#007700" });
  cylinder.geometry = new THREE.CylinderGeometry(3, 3, 12, 25)
  scene.add(cylinder);
}

function animate() {
  cylinder.position.z -= 1;
  cylinder.rotation.x -= THREE.Math.degToRad(2);
  
  light.position.x = cylinder.position.x;
  light.position.y = cylinder.position.y + 100;
  light.position.z = cylinder.position.z;

  camera.position.x = cylinder.position.x;
  camera.position.y = cylinder.position.y + 10;
  camera.position.z = cylinder.position.z + 30;
  camera.lookAt(cylinder.position);

  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
body{
    width: calc(100vw - 16px);
    height: 100vh;
    margin: 0;
    padding: 0;
    border: 0;
    background: #aabbaa;
 }

canvas {
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/87/three.js">
</script>

Even though I want the light to be positioned above the cylinder in each frame, it quickly moves into darkness. What could be causing this issue?

Answer №1

Failure to set the spotlight's target can lead to unexpected results.

The documentation explains:

.target

The Spotlight points from its position to target.position. The default position of the target is (0, 0, 0).

Note: To change the target's position from the default, it must be added to the scene using

This means that when you move your light with the cylinder, it automatically points to the center of the scene as a default behavior.

To achieve the desired outcome, assign your cylinder as the light's target.

Create and position various elements in a WebGL scene. Initialize and animate the scene to produce dynamic effects and interactions.
Define CSS styling for the body and canvas elements. Specify display properties for proper rendering.
Include the Three.js library script to enable advanced 3D graphics capabilities in the web application.

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

Step-by-step guide on activating a button only when all form fields are validated

My very first Angular 5 project. I've gone through resources like: https://angular.io/guide/form-validation and various search results I looked up, only to realize that they are all outdated. In my form, I have several input fields such as: <for ...

Inject the value of a JavaScript array into an HTML element

Is it feasible to transfer a global javascript array value to an HTML tag, particularly within an img (title) tag? I'm curious if the following is achievable: <img src="_info.gif" height="26" width="37" title=myArray[5]/> If it is possible, p ...

Utilizing an AngularJS factory to retrieve JSON data from the server

I have a large JSON object in my controller that I want to move to a separate file. Currently, this is how I'm approaching it: myApp.controller('smController', ['$scope', function($scope) { ... var stadtmobilRates = { cla ...

Elements are not detected after applying display:none

Within the onLoad event, I implemented a function to hide multiple div elements by setting their CSS property display to "none" and assigning them the class name "invisible": function hideContent() { laElements = document.getElementById("content").chil ...

The jQuery function appears to be running multiple times in a loop

For some reason, every value in my JSON object is getting added to the "listOfCountries" array twice. It seems like there might be a loop going through the result object more than once. I could really use some assistance with this issue! var listOfCountri ...

Sending data to server with Backbone (using save() function and php script)

Wondering if you can assist me with an issue I'm facing. I am trying to utilize Backbone's save() method and send data to a php file. However, I encountered a problem right at the beginning. When I execute the following in the browser's co ...

Tips for setting up Highcharts tooltip.headerFormat using the function getDate() plus 5

I'm facing a little challenge trying to understand how the JavaScript function getDate interacts with Highcharts datetime on xAxis. My goal is to show two dates in the tooltip header, forming a date range like this: 1960/1/1 - 1965/1/1. The first da ...

Freezing the website by setting async to false

I've been having issues with my website freezing when using async set to false. I need confirmation before executing the script. $.ajax({ type: "POST", url: url, data: form.serialize(), async: false, success: function(data) { ...

Having trouble locating the CSS and JavaScript files within my Spring Maven project

I have a Spring framework application with a Maven project. In addition, I have CSS and JavaScript files under the WEB-INF folder. When attempting to link the JavaScript and CSS files like this: <link rel="stylesheet" href="../allDesign/js/vendor/anims ...

What could be the reason behind receiving a TypeError upon refreshing the page, where it claims that a state is not found even though that may not be the actual situation?

Within my application, I have a component called Wall. Users are redirected to the Wall component after successfully logging in from the Login component. In the Wall component, I am retrieving and displaying the user's name that they used during regis ...

The issue of WithRouter Replace Component not functioning in React-Router-V6 has been encountered

As I upgrade react router to react router v6, I have encountered a problem with the withRouter method which is no longer supported. To address this issue, I have created a wrapper as a substitute. export const withRouter = Component => { const Wrappe ...

In React js, I wanted to display the animation specifically on the "add to bag" button for the added item

When I click the "add to bag" button, all other buttons also display the animation. How can I make sure that only the clicked button shows the animation? Any suggestions? <Table responsive> <thead> <tr> ...

Differences between Angular's $injector and Angular's dependency injectionAngular

As a newcomer to Angular, I am exploring the use of $injector and its get function to retrieve specific services. For instance: app.factory('$myService', function($injector) { return { ... var http = $injector.get('$http&apos ...

Prevent refreshing Google Maps when changing routes in AngularJS

Utilizing a Google map as the background for my website adds a unique visual element to the data displayed on different routes. However, I have encountered an issue where the map reloads with every route change, resulting in an unsightly flash of white tha ...

Angular appends "string:" in front of value when using ng-options

In my HTML, I have a ng-options list set up with a select element like this: <select required="required" ng-model="vm.selectedOption" ng-options="item.name as item.label for item in vm.options"> <option value="">Select an opti ...

Is it possible to retrieve a static resource within server-side code in NextJs?

Exploring the static render feature of NextJS to generate a static version of my website has led me to ensure that all necessary data is provided for the initial page render. I have stored several blog posts as .md files in /static and aim to access them ...

The ng-include directive is having trouble finding the partial HTML files

I've been working on setting up a basic tabset with each tab pulling content from a separate partial view with its own controller. To test everything out, I created three dummy HTML files with simple text only. However, I'm having trouble getting ...

Leveraging a service variable in Angular

Is there a way to access data shared in a service within a directive? Let's say we have a directive called resultsDirective, and a service named dataService. How can we retrieve a variable from the service within the directive? angular.module("someMo ...

MUI React - Issue with changing SvgIcon color using override

Currently, I am utilizing MUI version 5 within a React project. My objective is to customize the icon color for the Error Alert by using General StylesOverrides. Although I successfully altered the color on the Alert component, I am unable to discover a ...

`Using top-level await in a module can interfere with the firing of the `onload` event

It seems that the load event is not triggering when I use await for an IndexedDB opening at the top level within an indirectly loaded module. Interestingly, if I remove the await, the load handler works as expected. Similarly, replacing the openDB call wi ...