Exploring the world of lighting and shadows in WebGL and Three.js

I'm having difficulty focusing lights on specific targets, specifically the main character, while also darkening the background. Additionally, I'm experiencing issues with the shadows not working properly in my code snippet related to lights and shadows. Any suggestions?

Check out this portion of the index.html file:

//////////////////////////////////////////////////////////////////////////////////
//      renderer setup                          //
//////////////////////////////////////////////////////////////////////////////////

var renderer    = new THREE.WebGLRenderer();
renderer.shadowMapEnabled = true;
renderer.shadowMapType = THREE.PCFSoftShadowMap;
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

//////////////////////////////////////////////////////////////////////////////////
//      default 3 points lightning                  //
//////////////////////////////////////////////////////////////////////////////////

var ambientLight= new THREE.AmbientLight( 0x020202 )
scene.add( ambientLight)

var frontLight  = new THREE.DirectionalLight('white', 1)
frontLight.position.set(0.5, 0.5, 0.5)
frontLight.castShadow = true
scene.add( frontLight )

var backLight   = new THREE.DirectionalLight('white', 0.5)
backLight.position.set(-0.5, -0.5, -0.5)
scene.add( backLight )

frontLight.shadowMapSize = new THREE.Vector2( 512, 512 )
frontLight.shadowCamera = new THREE.OrthographicCamera( 0, 0, 0, 0, 0.5, 500 )

var pointLight  = new THREE.SpotLight('white', 0.1)
pointLight.position.set(0,5,5)
scene.add( pointLight )

//////////////////////////////////////////////////////////////////////////////////
//      obstacle (short version)                                            //
//////////////////////////////////////////////////////////////////////////////////

scene.add(obstacle)
obstacle.position.x = 0.00
obstacle.castShadow = true

//////////////////////////////////////////////////////////////////////////////////
//      Init floor                  //
//////////////////////////////////////////////////////////////////////////////////
function generateRoad(z){
    var road = THREEx.Environment.road()
    road.receiveShadow =  true
    scene.add(road)
    var velocity    = new THREE.Vector3(0, 0, z);
    road.position.add(velocity)
}

Answer №1

Your code is mostly working, but there is a problem with the shadow camera. It currently has a range of 0.0 in both the x and y directions. To fix this, you can use the following snippet:

frontLight.shadow.camera = new THREE.OrthographicCamera( -10, 10, 10, -10, 0.5, 500 );

If you refer to

https://threejs.org/docs/#api/cameras/OrthographicCamera
, you'll see that it defines a view matrix and an orthographic projection matrix.

The projection matrix is responsible for mapping 3D scene points to 2D viewport points. It transforms from view space to clip space, and then to normalized device coordinates (NDC) within the range of (-1, -1, -1) to (1, 1, 1) by dividing with the w component of the clip coordinates. Any geometry outside of NDC is clipped.
In Orthographic Projection, eye space coordinates are linearly mapped to normalized device coordinates.

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

In your current setup using

THREE.OrthographicCamera( 0, 0, 0, 0, 0.5, 500 )
, the values for left, right, top, and bottom are all set to 0. This essentially tries to map the area between 0.0 and 0.0 to the NDC.


Check out the provided code snippet:

// Your JavaScript code goes here
// ...
<script src="https://threejs.org/build/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

<div id="WebGL-salida"></div>

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

What is the best way to create a fixed sidebar or top bar that remains visible as I move to different pages?

Whenever I navigate to other pages, the sidebar mysteriously disappears. As I work on my project about an admin page, I'm wondering if it's necessary to include every single page? ...

Issues with JQuery Ajax rendering in browser (suspected)

I'm encountering an issue on my webpage. I have a div with two hidden fields containing values of 0 and 2, respectively. Upon clicking a button that triggers an AJAX query, the div contents are updated with hidden field values of 1 and 2. However, it ...

Employing multer in conjunction with superagent to enable file uploads from a React application

I am new to using multer and experiencing some difficulties with it. My goal is to upload an image file from a react client using the superagent library to my server. However, the req.file data always shows as undefined in my code: On the server side : ...

Exploring the seamless integration of Material UI with React version 18

I am having an issue with my background not turning black in React version 18.2.0 when using makeStyles from Material UI version 4. Despite no errors in the code, the background remains unchanged. How can I fix this problem? import './App.css'; i ...

Is there an effective way to merge two collections?

I came across an issue where I am attempting to merge two arrays that resemble the ones listed below: var participants = [ {id: 1, name: "abe"}, {id:2, name:"joe"} ]; var results = [ ...

What is the process for customizing the appearance of a prop within the <TextField> component?

Using my custom DatePicker.js component, I have two instances of <TextField>. When the user clicks on the <CalendarIcon> within the <TextField>, a small calendar pops up. However, I want to style the label in the <TextField> in a sp ...

The issue of Ng-Route not functioning properly on a Node/Express static server

I need assistance with my app.js file that currently directs all requests to pages/index.html. Now I am attempting to utilize Angular to route user requests for '/#/media' by adding the following code: academy.config(function($routeProvider) { ...

Ensure that all MongoDB write operations have been completed before proceeding with a find operation

I am in need of a store js object that can manage a mongodb collection in a specific way: store.insert(thing); // triggered from a pubsub system without waiting for the insert to complete store.get(); // should return a promise that resolves to the items ...

The server encountered an unexpected error while processing the request, possibly due to a

My JavaScript file includes an interval function that calls the following code: setInterval(function() { $.getJSON('/home/trackUnreadMsgs', function(result) { $.each(result, function(i, field) { var temp = "#messby" + result[i].from; ...

Is there a way to alter visibility once a radio button has been selected?

I have a shape resembling a cube with 4 faces, all of which are currently visible. However, I would like to hide the other 3 faces when one face is showing. For example: I attempted setting the opacity of the other cube sides to 0 when the first radio but ...

Bootstrap Collapse function might not function properly immediately following the execution of Collapse Methods

Here is the reference link: http://jsfiddle.net/72nfxgjs/ The code snippet I used is from w3schools: http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_js_collapse&stacked=h <script type="text/javascript"> $("#collapse1").col ...

Tips for saving information in an array with Vue.js?

I am working on a task where I need to fetch data from an API and store only the values that are marked as "true" in a variable. The API response is listed below: API Output Data { "BNG-JAY-137-003": false, "BNG-JAY-137-004": true, ...

Jade iterates over each object element, assigning its children to their respective parent elements

I have a JavaScript Object named "boards". [{"id":1,"parent_board":0,"title":"Lorem 1","description":"ec40db959345153a9912"}, {"id":2,"parent_board":0,"title":"Lorem 2","description":"bb698136a211ebb1dfedb"}, {"id":3,"parent_board":1,"title":"Lorem 1-1"," ...

Is it necessary to store tokens in cookies, local storage, or sessions?

I am currently utilizing React SPA, Express, Express-session, Passport, and JWT. I find myself puzzled by the various client-side storage options available for storing tokens: Cookies, Session, and JWT/Passport. Is it necessary to store tokens in cookies, ...

What is the most effective way to retrieve IDs from Firestore and add them to the object arrays?

Currently working on a project that involves React and Firestore, I'm attempting to retrieve the Ids back into the objects array. Below is the code snippet: function grabIds() { setIsLoading(true); reference.onSnapshot((querySnapshot) => ...

What could be causing the lack of animation in W3schools icons?

I've followed the steps provided and even attempted to copy and paste them. However, I'm experiencing an issue where the animation doesn't fully execute. Instead of the bars turning into an X shape, they reset halfway through the animation. ...

Avoid adding any empty entries to the list using jQuery

I have implemented a code to prevent any blank entries from being added to my list, and it seems to be working fine. However, I can't shake the feeling that there might be a better way to achieve this. Even though it functions correctly, it doesn&apos ...

Effortlessly navigate between Formik Fields with automated tabbing

I have a component that validates a 4 digit phone code. It functions well and has a good appearance. However, I am struggling with the inability to autotab between numbers. Currently, I have to manually navigate to each input field and enter the number. Is ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

Cache for AngularJS $http.jsonp requests

I'm struggling with caching a JSONP request and have tested out different approaches without success. I attempted $http.jsonp(url, { cache: true }) and $http({ method: 'JSONP', url: url, cache: true }), but neither worked as expected. As a ...