Having trouble getting Three.js JSON models to cast shadows properly?

Recently, I've been experimenting with blender exported models in Three.js. I have successfully imported a model and observed how light interacts with the object. While a directionalLight is illuminating the front-facing parts, I'm facing an issue with casting shadows.

Here's what I've set up:

renderer.shadowMapEnabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
(...)
var directionalLight = new THREE.DirectionalLight(0xffffff);
directionalLight.position.set(30,10,-10);
directionalLight.castShadow = true;
directionalLight.shadowDarkness = 0.5;
directionalLight.shadowCameraVisible = true;
directionalLight.shadowBias = 0.1;
directionalLight.shadowMapWidth = 1024;
directionalLight.shadowMapHeight = 1024;
directionalLight.shadowCameraRight = 10;
directionalLight.shadowCameraLeft = -10;
directionalLight.shadowCameraTop = 10;
directionalLight.shadowCameraBottom = -10;
directionalLight.shadowCameraFar = 10;
directionalLight.shadowCameraNear = 10;
scene.add(directionalLight);

var loader = new THREE.ObjectLoader();
loader.load("island.json", function(geometry) {
    islandMesh = geometry;
    for(k in islandMesh.children-1){
        islandMesh.children[k].castShadow = true;
        islandMesh.children[k].receiveShadow = true;
    }
    islandMesh.castShadow = true;
    islandMesh.receiveShadow = true;
    scene.add(islandMesh);
    render();
});

Despite setting up what I believe to be the necessary configurations for shadow casting, I am unable to see any shadows being cast. See the screenshot below:

https://i.stack.imgur.com/9pvxC.jpg

Even though the light source is positioned to the right of the island, the mountains are not casting the expected shadows.

Any help or insight on this matter would be greatly appreciated!

Thank you so much in advance!

Answer №1

To successfully implement your code, it is crucial that the data in your json file follows a specific structure where there is one parent and all other elements are children of that parent. (It is curious why you are decrementing in the for loop using -1.)

A more robust approach for all scenarios would be to navigate through the generated geometry tree:

islandMesh.traverse ( function (child) {
    if (child instanceof THREE.Mesh) {
        child.castShadow = true;
        child.receiveShadow = true;
    }
}

Update

In regards to the directional light being utilized, adjustments may need to be made to the

light.shadowCameraNear, light.shadowCameraFar, light.shadowCameraLeft,
light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom

The default values for CameraNear might suffice, but consider setting it back to 1. As for CameraFar, the value should depend on the distance between the camera and the farthest point in the scene.

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

A guide on incorporating recursion to nest dictionaries within current data records

Currently, I am in the process of converting XML data from Open Street Map into JSON format to upload it into a database. Due to the size of the data, I am using iterparse for parsing. However, I have encountered some tags that have a specific structure li ...

Uploading files asynchronously in Internet Explorer 8

Currently, I am on the lookout for sample code that allows asynchronous file uploads in IE8 using Ajax. While having upload progress would be a bonus, it is not essential. Moreover, I specifically need PHP code to handle the uploaded files on the server ...

Retrieve JSON data from an SQL query that includes the term "MariaDB."

If I have a row named "weather" in a MariaDB table with the following information: "Weather today is Sunny - {“temp”: “79”, “rainchance”: “0%”}", how can I extract ONLY the JSON data? I attempted 'JSON_VALUE(weather,'$.temp' ...

Query parsing in JSON using the Elasticsearch Java API is what we need to focus

As I work with an elasticsearch database to store Contacts, I execute the following query. public String getAllContacts() throws IOException { SearchResponse response = client.prepareSearch("contact").get(); return response.toString(); } After ...

ReactJS sidebar navigation functionality

I have a fixed sidebar with icons for navigating to different pages. When an icon is clicked, a secondary menu slides out. However, the issue is that when another icon is selected, the menu slides back in instead of switching or staying out. Additionally, ...

Troubleshooting: Unable to modify value with function in AngularJS

Why can't I change a value using a function in AngularJS? html: <div ng-controler='TestCtrl' id='TestCtrl'> <h1>Test: {{test.name}}</h1> <div ng-hide='showTest'> <div class=&a ...

Choosing a row in a table with ASP.NET by utilizing jQuery on click

After setting up a table in ASP.NET with the feature to select individual rows using a link at the end of each row, I have been able to successfully implement it. The process involves setting a value at the top of the view and then dynamically changing the ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

Verifying that JSON keys are in lowercase format within the .NET framework

Is there an easy way to ensure that JSON keys are sent as lowercase in .NET? Currently, I am using the Newtonsoft's Json.NET library and utilizing string loginRequest = JsonConvert.SerializeObject(auth); Here, auth is just a simple object like this ...

Struggling to create a SVG Line with DOM Manipulation in Typescript

I'm having trouble adding an SVG element to my div using the appendChild function in TypeScript. I want to add a line inside the SVG, but for some reason, I can't see the line output on my browser. There are no errors showing up either. Please he ...

What causes an "Internal Server Error" when attempting to use data for a database request with AJAX GET/POST in Laravel?

There's a unique issue that I'm struggling to resolve... Every time I drag and drop an event into the calendar, an Ajax Post Request is sent to my controller. The controller then inserts some data into the database with the event name received v ...

AngularJS directive created for validation on blur

I am striving to replicate some of the features found in Angular 1.3.X for the app I am developing, with a particular focus on ensuring compatibility with IE 8. Unfortunately, this constraint means that I cannot utilize version 1.3.X. I have encountered di ...

Issues with data binding in Angular2 are arising specifically in IE11

After successfully loading the application on Chrome, Firefox, and Edge, I encountered difficulties when trying to load it on IE11. The data bindings were not created properly, despite the internal data being fetched correctly through a websocket connectio ...

retrieve serialized data using jQuery in C# webforms

Is there a way to retrieve jQuery serialized data in C# webforms code behind? I have attempted the following: jQuery.ajax({ type: "POST", url: "book_de_acoes.aspx/salvarSimulacaoAutomatica", data: JSON.stringify({ form: ...

Unable to render HTML through Jquery ajax functionality

success: function(json) { for (var i = 0; i < json.length; i++) { var response = json[i]; $('#rv-container').html('<p>' + response.name + '</p>' + '<span>' + response ...

A versatile jQuery function for extracting values from a :input selector

Is there a universal method in jQuery to retrieve the value of any :input element? I pose this question because I have a webpage containing select and checkbox inputs, as seen in the code below: for (var i = 0; i < arguments.length; i++) { ...

refresh polymer components or make an ajax request within a custom element

I've been spending days on this issue with no success! My application relies on cookies for session handling and includes multiple custom elements imported in the header. Some of these elements need to access information from the 'cookie session& ...

Having issues with JavaScript and MySQL data retrieval following XMLHttp update to the database

After running the newNet.php file successfully creates a new entry and assigns it an auto-incremented netID. The next step is to retrieve this newly created ID and use it in the showActivities() function to display the record. Ideally, it should work like ...

Access information within the collection view

After downloading data from a JSON File, it is now stored in an object specific to that data. The goal is to access this data in a collectionView upon clicking on it. The question arises whether the data needs to be made globally available for all function ...

Command for controlling volume in DiscordJS

Despite my efforts, I am struggling to write a command that successfully changes the volume of the music being played. Every time the player and resource variables in the volume() function are empty while the bot is playing the song. What can I do to resol ...