Experiencing some unusual shadows in my Three.js project while attempting to add a simple shadow effect to a cube or group of cubes

Trying my hand at implementing shadows in Three.js, even though I am fairly new to JavaScript. My attempts to create a cube with a proper shadow have yielded partial results, as only a portion of the mesh seems to be casting the shadow.

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

The expected shadow should resemble something like this: https://i.sstatic.net/LqbGq.png

I've configured two lights to cast shadows, along with a hemisphere light to enhance brightness. Despite referencing various tutorials and questions to set up the materials correctly, I am still struggling to achieve the desired outcome.

The shadows overall appear satisfactory, but they appear to only cover a portion of the object. Any direct guidance or links to detailed tutorials on this fundamental topic would be greatly appreciated. I even tried using an official example, but couldn't make it work after removing the object from their code. (Specifically this one: Link to official example

For more details, I am using an M1 MacBook Pro and encountering this issue on both Safari and Firefox.

Here is the script I am currently working with:

<!-- importmap added by TheJim01 -->
<script type="importmap">
{
  "imports": {
    "three": "https://threejs.org/build/three.module.js",
    "three_orbitControls": "https://threejs.org/examples/jsm/controls/OrbitControls.js"
  }
}
</script>
<script type="module">
import * as THREE from 'three';
import { Object3D } from 'three';
import { OrbitControls } from 'three_orbitControls'; // TheJim01 modified to use importmap

// Establish Scene
var scene = new THREE.Scene();
scene.background = new THREE.Color( 0xD3D3D3 );
scene.fog = new THREE.Fog( 0xa0a0a0, 10, 2000 );

// Add Ground
const ground = new THREE.Mesh( 
    new THREE.PlaneGeometry( 1000, 1000 ), // geometry
    new THREE.MeshPhongMaterial( {  //material
        color: 0xFFFFFF, 
        depthWrite: false 
    } ) );

ground.rotation.x = - Math.PI / 2;
ground.receiveShadow = true;
scene.add( ground );

// Add directional lighting
const light = new THREE.DirectionalLight( "#FFFFFF", 1.25 );
light.position.set(-25, 50, 30);
light.castShadow = true; // default false

//Set up shadow properties for the light
light.shadow.mapSize.width = 512; // default
light.shadow.mapSize.height = 512; // default
light.shadow.camera.near = 0.1; // default
light.shadow.camera.far = 500; // default
scene.add( light );

const secondLight = new THREE.DirectionalLight ( "#FFFFFF", 0.5 );
secondLight.position.set(20, 30, -50);
secondLight.castShadow = true;

//Set up shadow properties for the light
secondLight.shadow.mapSize.width = 512; // default
secondLight.shadow.mapSize.height = 512; // default
secondLight.shadow.camera.near = 0.1; // default
secondLight.shadow.camera.far = 500; // default
scene.add( secondLight );

// Add hemisphere light
const hlight = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1.5);
const helper = new THREE.HemisphereLightHelper( hlight, 1 );
//scene.add( helper );

//Set up shadow properties for the light
light.shadow.mapSize.width = 512; // default
light.shadow.mapSize.height = 512; // default
light.shadow.camera.near = 0.1; // default
light.shadow.camera.far = 500; // default

// Camera
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
const renderer = new THREE.WebGLRenderer({ antialias: true });
camera.position.z = 25;
camera.position.x = 25;
camera.position.y = 25;
camera.lookAt(0,0,0)

// Renderer
renderer.setSize( window.innerWidth , window.innerHeight );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.shadowMapSoft = true;
renderer.shadowMapBias = 0.0039;
renderer.shadowMapWidth = 1024;
renderer.shadowMapHeight= 1024;
document.body.appendChild( renderer.domElement );


const controls = new OrbitControls( camera, renderer.domElement );


// Cube
const material = new THREE.MeshPhongMaterial({
    color: 0xC8FAFF,
    roughness: 10,
  })

const geometry_1 = new THREE.BoxGeometry( 4, 5, 6 );
const cube1 = new THREE.Mesh( geometry_1, material );
cube1.position.set(
    -5, // Width
    0.5 * cube1.geometry.parameters.height, // Height
    0); // Depth
cube1.castShadow = true;
cube1.receiveShadow = true;
scene.add( cube1 );


//animate the scene
function animate() {
    requestAnimationFrame( animate );
    controls.update();
    renderer.render( scene, camera );
}


animate();
</script>

Answer №1

Discovered that the issue stemmed from shadows being clipped, as pointed out by @WestLangley.

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

Uncertain about how to transfer data between server and client in Next.js?

I'm currently grappling with understanding the proper method of exchanging data between server-side and client-side components in NextJS 13. To simplify my learning process, I have created a basic scenario. In this setup, I have two functions that pe ...

Is there a way to execute a JavaScript function on a webpage using Selenium automation?

Here's an element on a website: <span class="log-out-ico" ng-click="logout()"> Instead of clicking it, I want to run the "logout()" script from selenium. Is that possible? If so, how can I do it? This is what I attempted: I ...

"Utilizing Angular's $http.post to extract data from resolved promises

Can you help me figure out how to successfully send data through $http.post that I receive from a function using $q.defer()? Here is the code snippet: HTML <input type='text' ng-model='name'/> <input type='file' id= ...

Different Angular 2 components are resolved by routes

Consider this scenario: Upon navigating to the URL /product/123, the goal is to display the ProductComponent. This is how it's currently configured: RouterModule.forRoot([ { path: 'product/:productId', ...

Selection of Dropdown results in PDF not loading

I am facing an issue with my function that selects a PDF from a dropdown list. Instead of loading and displaying the PDF, it only shows a blank modal. Any suggestions on how to fix this? <li> <a href="">Case Studies</a> <ul clas ...

What is the best way to utilize typed variables as types with identical names in Typescript?

Utilizing THREE.js with Typescript allows you to use identical names for types and code. For instance: import * as THREE from '/build/three.module.js' // The following line employs THREE.Scene as type and code const scene: THREE.Scene = new THRE ...

How can one selectively apply a class to the initial DIV within a collection of dynamically generated DIV elements without relying on jQuery?

I am currently working on implementing a slideshow within a modal using AngularJS and Bootstrap. My challenge lies in dynamically creating DIVs, but specifically adding the active class to only the first DIV. Is there a way to achieve this without relying ...

Extracting Data from Input Box Using Query

In my HTML setup, I have five <textarea> tags with IDs text1,text2,text3,text4, and one additional <textarea> tag with ID output. I want to query based on the values of text1,text2,text3,text4 (referred to as field1, field2, field3, field4). F ...

The function causes an unexpected alteration in the coordinates of polygons on a leaflet map

I have been working on enhancing the functionality of a leaflet map by adding triangles with specific rotations to each marker that is created. The code snippet below demonstrates how I achieve this: function add_items_to_map( to_map, longitude, latitude, ...

The resize() function in jQuery triggers a stack overflow exception

I am trying to manage the resizing of a div on my website, but I am encountering a stackoverflow exception when using the resize function. Can someone please help me understand what I am doing wrong? For reference, here is a jsfiddle example: https://jsfi ...

Developing pledges in AngularJS

I am currently working on implementing a promise in Angular using the $q service to retrieve an object from a web service. The unique aspect of this implementation is that if the object is already cached, it should be returned without making a call to the ...

The slider thumb is not showing up properly on Microsoft Edge

Hey there! I'm experiencing an issue with the range slider's thumb display in Microsoft Edge. It appears to be positioned inside the track rather than outside as intended. Take a look at this snapshot for clarification: https://i.stack.imgur.co ...

The click listener triggers a single time when a render method is nested within it

When I have a click listener on a button that resets the innerHTML of a div with a render method, the listener fires every time I click if I take out the render function. However, if the render function is included, the listener does not fire multiple time ...

Locate and retrieve a document by its unique identifier in MongoDB, and then store its information in an array

I am working with two models: Meal and Ingredient. Let's take a look at their schemas: const mealSchema = new Schema({ title: { type: String, required: true }, image: { type: String, required: false }, ingredients: [{ ingredient: { ...

I am having trouble getting Stripe Elements to function properly within Laravel

I'm currently developing a subscription app using Laravel and trying to integrate Stripe Elements, but I'm encountering issues with getting it to function properly. Below is my form: <form method="POST" action="/subscribe" id="payment-form"& ...

"An intermittent error is occurring with the jQuery webcam plugin, where a TypeError is being thrown stating that

Many times, I encounter the error stated in the subject line. The code snippet where this error occurs is within the else section of the function below: if ($('#clicktosnap').is('.disabled')) { alert ("Please enable the camera first, ...

What are some techniques for styling a field when the div id is not specified?

I need to customize a data field within a table, but I am unable to locate or identify its div ID. Here is the page source: <tbody> <tr> <td style="font-size:12px; text-align:center;" name=""> <div sty ...

When the mouse is clicked, the character fails to reach the intended destination or moves in the wrong direction on the HTML canvas

UPDATE: RESOLVED I am currently working on a game where the character moves by right-clicking. The character is meant to walk slowly, not teleport, towards the destination set by right-clicking on the canvas. However, I have encountered an issue where the ...

Challenges encountered while using Selenium WebDriver to upload images

I'm having trouble adding an image as a normal attachment to an email (not as an inline image). When inspecting the HTML DOM with Firebug, I noticed there are two elements with xpath //input@type='file', which is due to the presence of two b ...

Having trouble importing OrbitControls in three.js with an error?

I'm currently working on localhost and I've encountered an issue while trying to import "orbitcontrols()" which is not functioning properly and displaying an error. Here is the error message main.js:1 Uncaught SyntaxError: Cannot use import stat ...