Adding shadows to a GLTF model in THREE.JS - How do I achieve this effect?

Just starting out with Three.js and I'm trying to figure out how to make my GLTF model cast a shadow on itself. I've been experimenting with different approaches, but not sure if I'm on the right track. The light is set as a PointLight and the camera is a Perspective view - not sure if that detail matters. Can someone review my code below and provide any guidance? Much appreciated :)


var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(
        60,
        window.innerWidth / window.innerHeight,
        0.01,
        1000
    );
    //camera.rotation.x=-20*Math.PI/180;
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;
    document.body.appendChild(renderer.domElement);


    window.addEventListener('resize', () => {
        renderer.setSize(window.innerWidth, window.innerHeight);
        camera.aspect = window.innerWidth/ window.innerHeight;
        
        
        camera.updateProjectMatrix();
    });


    function mousemovement(event) {
        const mouseX = (event.clientX / window.innerWidth) * 2 - 1;
        const mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
  
        light.position.x = mouseX * 11 + 2 ;

       light.position.y = mouseY * 4 + 4.5 ;
    };

    var numberofclicks = 2;

    window.addEventListener('mousemove', mousemovement);
    
    window.addEventListener('click', e =>{
        numberofclicks = numberofclicks + 1;
        if(numberofclicks % 2 == 0) {
    window.addEventListener('mousemove', mousemovement);
    }
    else {
    window.removeEventListener('mousemove', mousemovement);
    }
    });

    

    //GLTF model
    var loader = new GLTFLoader();

     loader.load("wrktblv2.gltf", function (gltf) {

            loader.castShadow = true;
            loader.receiveShadow = true;
         scene.add(gltf.scene);

     });
     
     var light = new THREE.PointLight(0xffffff, 2, 20);
     
     light.position.set(1,10,2)
    
     scene.add(light);
     
     camera.position.set(2,3,9);

     
     
        //const lightHelper = new THREE.PointLightHelper(light);
        //const gridHelper = new THREE.GridHelper(200,50);
        //scene.add(lightHelper, gridHelper);
     
    function animate(){
         requestAnimationFrame(animate);
         renderer.render(scene,camera);      
     }
     animate();

Appreciate your help! Cheers!


Edit--Managed to add shadows, but ran into another issue.


Click here to view the issue.

Answer №1

To enhance the lighting effects, make sure to include light.castShadow = true. It's important to note that shadows should be cast on individual meshes rather than on the loader itself. To achieve this, update the code as follows:

loader.castShadow = true;
loader.receiveShadow = true;

Replace the existing code with the following:

gltf.scene.traverse(function(child) {
    if (child.isMesh) {
      child.castShadow = true;
      child.receiveShadow = true;
    }
})

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

Substitute the Iframe element with Ajax technology

Currently, I am working on a project where I want to include previews of various websites within my own website. Right now, I am using Iframes to load the website previews and allow users to interact with them. For SEO purposes, I have decided to replace ...

Fluctuating Values in Array Distribution

I have a set of users and products that I need to distribute, for example: The number of values in the array can vary each time - it could be one value one time and three values another time. It is important that each user receives a unique product with ...

Tips for connecting 2 Bootstrap 5 carousels

I currently have 2 Bootstrap 5 carousels (carousel-a & carousel-b) on the same page and I want them to be synchronized with each other. I believe this can be achieved using JavaScript, but I am not very familiar with it. Below is the structure of carousel- ...

Logging to the console using an If/Else statement, with the Else block containing code that

I'm encountering a peculiar issue with my If statement. I'm modifying the state (true/false) of an object based on onMouseEnter and onMouseLeave. I can execute the code when it's true, but if I include any code in the else statement, it ma ...

An unanticipated issue has arisen with the Alert Open Error. The command "browser.switchTo().alert().accept();" functions properly in Firefox, but encounters difficulties in Chrome while executing via Jenkins

Seeking assistance on how to resolve a specific error encountered in the Chrome browser while using Protractor. https://i.stack.imgur.com/7Fm4l.png The error message reads as follows: "UnexpectedAlertOpenError: unexpected alert open: {Alert text : There a ...

The LatinSquare.js script has exceeded the maximum call stack size limit

In my current project, I am utilizing the latin-square library for node.js within a loop to search for a specific pattern. However, I encountered an error after running the script for 2 minutes: RangeError: Maximum call stack size exceeded var latin ...

Updating HTML5 localStorage value upon a click

Currently, I have implemented a countdown timer using the provided code snippet. To prevent the count from resetting upon page refresh or reload, I am utilizing local storage. However, if there is an alternative solution to achieve this functionality, I wo ...

Utilize an A-frame conditional statement to check a variable and dynamically display various glTF models depending on its value

Is it possible to use JavaScript and A-frame () to create a scenario like this? I want to have an onload function named load() that will evaluate the value of variable x. If x is equal to one, I want the gltf with the ID of 1 to be visible while hiding th ...

Ways to identify when the socket has been opened by the client?

When utilizing socket.io on the client browser side, is there a way to identify when the socket connection has been successfully opened? I am also interested in monitoring other standard messages such as errors and disconnections. In comparison to the Web ...

Efficient methods for transferring information between a main and pop-up page within angularjs

On my webpage, I have a button that opens a popup page. I need to figure out a way to transfer json data from the main page to the popup page. These two pages are running separate angular applications. Once the data is transferred, it will be updated base ...

Successive vows

I'm trying to retrieve responses from four promises, but I currently have to call each function in sequence one after the other. In my code, you can see that I trigger the next function within the promise callback of the previously called function. H ...

<dt> and <dd> have not been added after the previous element

I can't seem to figure out why the dt and dd elements are not being added to the dl I created. Here's my initial attempt: // Dictionary list var words = [ { term: "Procrastination", definition: "Pathological tendency to s ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

Observing the state object in Pinia does not trigger when the object undergoes changes

I am facing an issue with setting a watcher on a deeply nested object in my Pinia state. export const useProductStore = defineStore("product", { state: () => ({ attributes: {}, }), }); When the object has data inside it, it looks something like ...

Incorporate tinyMCE into a colorbox module

Currently, I am facing an issue on my website where there are textareas with tinymce. While I can view all the textareas correctly, when trying to open colorbox within a textarea, it does not inherit the tinymce properties. The code snippet used to open co ...

Tips on effectively centering a wide div

After much experimentation, this is what I came up with: (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en ...

Detecting Scroll on Window for Specific Element using Jquery

I need help troubleshooting my code. I am trying to activate only one item that comes from the bottom of the page, but instead all div elements are getting activated. $(window).scroll(function() { $('.parallax').each(function(e) { if($( ...

"Encountered a problem during the installation of pm2 for Node.js

I am in the process of installing pm2 (https://github.com/Unitech/pm2) Encountered the following error while doing so: D:\_Work>npm install pm2 -g --unsafe-perm npm WARN `git config --get remote.origin.url` returned wrong result (http://ikt.pm ...

Fully responsive header designed for optimal experience at any screen height

I am facing issues with the header and cannot seem to find a solution. My goal is to make the header span 100% of the window screen height. I need a responsive header that adjusts to 100% height, and when resizing for a smaller viewport, nothing should sho ...

Executing the Angular 2 foreach loop before the array is modified by another function

Currently, I am facing some difficulties with an array that requires alteration and re-use within a foreach loop. Below is a snippet of the code: this.selectedDepartementen.forEach(element => { this.DepID = element.ID; if (this.USERSDepIDs. ...