I am unable to illuminate with a mouse event

I'm encountering an issue where I can't add light using the keydown event in a three.js scene.

Here's the function that I am using:

function putLight(){
    light = new THREE.SpotLight( 0xffffff );
    light.position.set( 10, 80, 20 );
    light.target.position.set( 0, 0, 0 );

        light.castShadow = true;

        light.shadowCameraNear = 20;
        light.shadowCameraFar = 50;
        light.shadowCameraFov = 40;

        light.shadowMapBias = 0.1;
        light.shadowMapDarkness = 0.7;
        light.shadowMapWidth = 2*512;
        light.shadowMapHeight = 2*512;
    scene.add( light );
}

The function works perfectly when included in my init function:

function init(){
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
    scene = new THREE.Scene();
geometry = new THREE.PlaneGeometry( 300, 300, 50, 50 );
    geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );

    material = new THREE.MeshLambertMaterial( { color: 0xdddddd } );

    mesh = new THREE.Mesh( geometry, material );

    mesh.position.copy(groundBody.position);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    scene.add( mesh );


    renderer = new THREE.WebGLRenderer();
    renderer.shadowMapEnabled = true;
    renderer.shadowMapSoft = true;
    renderer.setSize( window.innerWidth, window.innerHeight );

    document.body.appendChild(renderer.domElement);
}

It also executes correctly if placed outside any function in the main script:

initCannon();
init();
loadModel();
putLight();
render();

However, there seems to be a problem when trying to call it within the keydown event listener:

window.addEventListener("keydown",function(e){
    switch( e.keyCode ) {
        case 76:
            putLight();
            break;
    }
});

Any ideas on how to resolve this issue?

Appreciate any suggestions!

Answer №1

When it comes to adding a light to your scene after rendering at least once, there are some considerations to keep in mind.

As mentioned in the official Wiki article How to Update Things with WebGLRenderer, certain properties, such as the number and types of lights, cannot be easily changed once a material has been rendered at least once.

If you find yourself needing to add a light after the initial render, make sure to set

material.needsUpdate = true;

Alternatively, you can also add the light before the first render and simply set its intensity to zero until needed.

This advice is based on three.js r.68

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

I'm encountering an issue with the "z-index: -1" property in React

After creating a form placed alongside buttons, I encountered an issue where the form overlaps the buttons and prevents them from being clicked. Despite setting the z-index to -1, it seems that the form remains clickable even when not visible. Research ind ...

JavaScript libraries are not required when using the .append function to add HTML elements

Currently, I am attempting to utilize $.ajax in order to retrieve an html string from a php file and append it to the current html div. Oddly enough, when I use php echo, everything functions properly. However, when I attempt to load dynamically using $.lo ...

Storing checkbox values in a MySQL database using PHP

I am working on a project that involves two checkbox filters. My goal is to keep track of the count of checked checkboxes for each filter and store this information in separate columns in a MySQL table. Could someone please assist me in obtaining the coun ...

How can Selenium be used to identify an Internet Explorer browser extension?

Can Selenium be used to detect internet explorer browser plugins? For example, if I open a URL on IE and want to check for any installed plugins, is there a way to automate this with selenium? ...

How to capture two values in JavaScript input fields

I have developed a dynamic checker that instantly verifies user inputs against the database to see if they are already in use (e.g. username, phone number) Here is an example of the input box: <input type = "text" name = "user_username" placeholde ...

Running a server-side function on the client-side in Node.js

I am currently working with the following code snippet on the server: var game = io.listen(app); game.sockets.on('connection', function(socket){ storePlayers(socket.id); //Only the player who connects receives this message socket.em ...

Toggle the font weight in a text area by clicking a button

I need help with creating a button that will change the font-weight to bold when clicked and then revert back to normal when un-clicked. However, I only want the specific part of the text area where the user clicks the button to be bolded, not the entire t ...

Build a flexible Yup validation schema using JSON data

I am currently utilizing the power of Yup in conjunction with Formik within my react form setup. The fields within the form are dynamic, meaning their validations need to be dynamic as well. export const formData = [ { id: "name", label: "Full n ...

ESLint: The "react" plugin encountered a conflict

In my development environment, I have a React application within a single npm component package. This React app acts as a demonstration site that consumes the component package in addition to Storybook. local-component-package ├── .storybook ├─ ...

Using Javascript to hide specific rows in a table

Question for Javascript beginners: I am aware that there are numerous ways to achieve this task, many of which are explained on various platforms. However, my question pertains specifically to the following code snippet. <html> <head> <scri ...

Why is it that a specific variable is only undefined in one specific location within the entire component?

import React from 'react'; import { Formik, Form } from "formik"; import { InputField } from "./formui/InputField"; import { applyGharwapasi } from "../../appollo/applyGharwapasi/applyGharwapasi"; import { useMutatio ...

Designate material for a particular table header element

Is there a method to pass content within a td-element to a specific th-element? I am working with a dynamic table and need to associate the content correctly under each table header. I have implemented pagination for the rows in the table. Currently, all ...

Calculate the character count of every string within an array

Here is the JavaScript code I wrote: var myArray = ["the", "quick", "brown", "fox"]; console.log(myArray.length); This is what I want the output to look like: [3, 5, 5, 3] ...

Managing the AJAX response from a remote CGI script

I'm currently working on a project that involves handling the response of a CGI script located on a remote machine within a PHP generated HTML page on an apache server. The challenge I am facing relates to user authentication and account creation for ...

Issue: EMFILE - exceeding maximum number of opened files

I'm currently working with nw.js, attempting to save images in an array of img tags with random names. However, I've encountered a few errors and I'm unsure what's causing them. for (i = 0; i < imgs.length; i++) { request(imgs[i].g ...

Aurelia TypeScript app experiencing compatibility issues with Safari version 7.1, runs smoothly on versions 8 onwards

Our team developed an application using the Aurelia framework that utilizes ES6 decorators. While the app works smoothly on Chrome, Firefox, and Safari versions 8 and above, it encounters difficulties on Safari 7.1. What steps should we take to resolve th ...

The animation freezes when trying to create geometry and mesh using Three.js

I'm currently working on developing a text animation that scrolls and dynamically adds more content as it runs. Here is the function I have created for generating the text geometry and mesh: function createText(){ textGeo = new THREE.TextGeometry( ...

Updating the state value of a variable that utilizes a custom Hook: a step-by-step guide

After watching a video by Dan Abramov, I decided to optimize my component by creating a custom Hook called useFormInput. This hook handles the state and onChange functionality for all of my form input fields. Everything was working perfectly until I neede ...

Implementing Vuetify tooltips in a datatable

Attempting to incorporate tooltips into a vuetify datatable, but encountering issues. Below is the required template for using a tooltip: <template v-slot:item.state="{ item }"> <div :class="lights(item)"></div> </template> Im ...

This TypeScript error occurs when the props are not compatible and cannot be assigned to

Hello fellow Internet dwellers! I am a novice in the world of coding and TypeScript, seeking some assistance here. I am attempting to extract an array of objects from props, transform it into a new object with specific information, and then return it - ho ...