What could be causing the shadow casting issue with a 3D model in three.js?

I am working with 3D models that are structured like this:

https://i.sstatic.net/osXTl.png

My goal is to incorporate a cast shadow similar to this:

https://i.sstatic.net/DBrRr.png

Here is the code snippet responsible for handling the model:

var ambLight = new THREE.AmbientLight( 0x404040 );
this.scene.add(ambLight)

var loader = new THREE.GLTFLoader();
loader.load(path,function (gltf) {
 gltf.scene.traverse( function( model ) {
  if (model.isMesh){ 
   model.castShadow = true; 
  }
 });
 this.scene.add(gltf.scene);
}

I implemented the castSHadow part based on guidance from this StackOverflow thread.

I have attempted using model.castShadow = true, as well as removing the if condition and solely having castShadow, but neither approach has yielded successful results. Is there a step I might be overlooking? For reference, the complete custom layer code can be found here.

Answer №1

  • Your scene lacks a shadow-casting light - consider adding an instance of AmbientLight for shadows.
  • To enable objects to receive shadows, ensure they have Object3D.receiveShadow set to true and are not using unlit materials like MeshBasicMaterial.
  • Don't forget to globally enable shadows with:
    renderer.shadowMap.enabled = true;

For guidance on setting up shadows, check out this official example.

Answer №2

After reviewing your code, it appears that you are attempting to overlay a shadow on top of Mapbox.

In addition to the advice provided by @Mugen87, you will need to create a surface below the model you are loading to hold the shadow. It is important to position this surface directly beneath the loaded object and take into account its size to prevent the shadow from extending beyond the surface. By following these steps, you should achieve the desired effect.

https://i.sstatic.net/wPD86.png

You can find the relevant code in this fiddle I have created. I made some adjustments to the lighting and included a light helper for improved clarity.

var customLayer = {
  id: '3d-model',
  type: 'custom',
  renderingMode: '3d',
  onAdd: function(map, gl) {
    // Code block shortened for brevity
  },
  render: function(gl, matrix) {
    // Transformation logic omitted for conciseness
  }
};

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

Change this npm script into a gulp task

I have a script in npm that I would like to convert into a gulp task. "scripts": { "lint": "eslint .", "start": "npm run build:sdk && node .", "posttest": "npm run lint && nsp check", "build:sdk": "./node_modules/.bin/lb- ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

"Proceeding without waiting for resolution from a Promise's `.then`

I am currently integrating Google Identity Services for login on my website. I am facing an issue where the .then function is being executed before the Promise returned by the async function is resolved. I have temporarily used setTimeout to manage this, b ...

Add multiple menu items dynamically to a dropdown menu in TinyMCE, with each menu item directing to the last item clicked when clicked

I'm currently utilizing tinymce along with tinymce-variable. My goal is to create a dropdown menu with dynamic menu items generated from an SQL database. Through a loop, I've managed to successfully create multiple dropdown menus by using editor. ...

Deleting a page reference from the page history stack in Angular 4

I am working on my angular web application and I am looking for a way to remove a specific page reference from the angular page history stack. For example, if I navigate from the login page to the dashboard page, I want to remove the login page reference f ...

Filtering Events using Radio Buttons in FullCalendar via JQuery

Currently, I am attempting to utilize a set of buttons in the JQUERY FullCalendar to filter events. My implementation successfully filters events based on the 'dog' or 'cat' category using a dropdown. However, I am struggling to achiev ...

Unable to invoke .then when simulating axios call within componentDidMount

I'm currently working on unit testing the componentDidMount method while simulating an Axios call. // src/App.tsx import axios_with_baseUrl from './axios-instance-with-baseUrl'; ... public componentDidMount() { axios_with_baseUrl.get(& ...

Retrieve an array from the updated scope

I need help with my code. How can I retrieve the names from an array and display them in my input box? Also, how do I get all the changed names back into the array? Thanks in advance! - Marco app.js var g[]; var names = ['John', 'Steve&apo ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...

AngularJS: Utilizing $http to fetch XML data instead of JSON

Looking to extract data from a website using angularjs / javascript. I am familiar with the $http object in angularjs which can make get requests. I have used it before to retrieve json, but I'm wondering if I can use it for XML (HTML) as well? (I th ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

TabContainer - streamline your selection process with inline tabs

I am currently working on a GUI that includes a TabContainer with two tabs, each containing a different datagrid. I initially created the tabcontainer divs and datagrids declaratively in HTML for simplicity, but I am open to changing this approach if it wo ...

The functionality of the TURF booleanwithin feature is malfunctioning and not producing the

Currently, I am working on validating whether a polygon is completely within another polygon. However, there are cases where more complex polygons should return false, but turf interprets them as valid. If you'd like to see the sandbox, click here: ...

Generate an array of objects by combining three separate arrays of objects

There are 3 private methods in my Angular component that return arrays of objects. I want to combine these arrays into one array containing all the objects, as they all have the same class. Here is the object structure: export class TimelineItemDto { ...

Conceal Pictures within Sources Section

On my webpage, I have included images with information about my project. To prevent users from downloading the images, I disabled the download option. However, users are still able to access all the images in the Sources tab by inspecting the page. Can a ...

PHP: Eliminating Line Breaks and Carriage Returns

My content entered into the database by CKEditor is adding new lines, which poses a problem as I need this data to be rendered in JavaScript as a single line of HTML. Within my PHP code, I have implemented the following steps: $tmpmaptext = $map['ma ...

The data retrieved from the $.ajax() request in Vue.js is not properly syncing with the table

After setting up an $.ajax() function and ensuring the data binding is correctly configured, I expected the data to append to a table on page load without any issues. However, the data is not appearing as expected. Is there something that I might be overlo ...

Inserting a value into a Node/Express session

I am currently immersed in a project that involves Node, Express, and MongoDB. Mongoose is the tool I use to shape my schemas and interact with the database. In addition, I utilize the "express-sessions" module where a session value named "req.session.user ...

How can you incorporate TypeScript's dictionary type within a Mongoose schema?

When using TypeScript, the dictionary type format is: { [key: string]: string; } However, when I try to define a custom schema in mongoose, it doesn't work as expected. const users = new Schema({ [key: string]: String, }); I also attempted t ...

What is the best way to pass values between JSP Expression Language and Javascript?

I have a request object with the following content: List<Integer> list What is the best way to loop through this list using JavaScript? I am interested in obtaining the values of each element within the list. Note that these list values are not cu ...