"Three.js Directional Light: Illuminating Your 3

I'm a newcomer to three.js and I've been experimenting with r55. I tried adding lights to my project by following Mrdoob's documentation, specifically using DirectionalLight. However, I'm facing an issue where the light doesn't show up despite adding shadowCameraVisible for debugging purposes. Can anyone provide insight on what might be going wrong with my code? Any help is appreciated!

function initialize() {
    container = document.createElement('div');
    document.body.appendChild(container);

    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    container.appendChild(renderer.domElement);

    // Creating a cube
    var material = new THREE.MeshBasicMaterial({
        color: 0xff0000
    });
    var geometry = new THREE.CubeGeometry(x, y, z);
    cube = new THREE.Mesh(geometry, material);
    cube.position.z = z / 2;
    scene.add(cube);

    // Creating a floor
    var floorMaterial = new THREE.MeshBasicMaterial({
        color: 0xcccccc
    });
    var floorGeometry = new THREE.PlaneGeometry(20, 20, 1, 1);
    var floor = new THREE.Mesh(floorGeometry, floorMaterial);
    floor.position.y = -0.5;
    floor.doubleSided = true;
    scene.add(floor);

    // Adding lights
    var dLight = new THREE.DirectionalLight(0xffffff);
    dLight.position.set(0, 0, 1);
    dLight.shadowCameraVisible = true;
    dLight.shadowCameraNear = 1;
    dLight.shadowCameraFar = 150;
    dLight.castshadow = true;
    scene.add(dLight);

    // Setting camera position
    camera.position.z = 50;
    controls = new THREE.TrackballControls(camera);

    renderer.shadowMapEnabled = true;
    renderer.shadowMapType = THREE.PCFShadowMap;

}

Answer №1

lightPosition.set = (0,0,1);

Oops, there seems to be an error here... if this code runs, the light position will not be set correctly as a 3-dimensional vector, resulting in calculations with the light position returning NaN.

lightPosition.set(0,0,1);
// or
lightPosition = new Vector3(0,0,1);

Answer №2

The adjustment of the light has been made by:

light.position.set (0,0,1);

It appears that the position of your light may be within the geometry rather than where intended. Please refer to http://jsfiddle.net/aSt8c/ for an example of a directional light with working shadows.

Answer №3

It is important to note that in order for your object to reflect light, the material must be either MeshLambertMaterial or MeshPhongMaterial. Other types of materials will not reflect light as effectively.


//SPHERE
    var shinyMaterial = new THREE.MeshPhongMaterial({
        color: 0x00ff00
    });
OR
    var nonShinyMaterial = new THREE.MeshLambertMaterial({
        color: 0x00ff00
    });

MeshPhongMaterial is suitable for creating shiny surfaces, while MeshLambertMaterial is better suited for non-shiny (Lambertian) surfaces.

Answer №4

In order to make it work, you must specify the following: floor.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

Regular expressions work when used on the internet, but they don't seem to

I'm encountering a peculiar situation with a regular expression. Here is the expression in question: const csrfRegex = /"csrf_token": "((\\"|[^"])*)"/ig; The main objective is to extract the CSRF token from a Javascript object on a website ...

My Ruby on Rails app seems to be malfunctioning in a major way

Instead of sharing code snippets, I’ve encountered difficulties in getting my jQuery code to work correctly. If you're curious, you can view the issues on Stack Overflow: Why doesn’t this jQuery code work? and This jQuery hide function just does n ...

What's the most effective method for isolating elements in HTML to prevent one element from impacting another?

I recently created a password form in HTML with some nice functions. However, after making a small adjustment, the CSS is causing the elements to shift when clicking on different input boxes. This results in the labels on the form moving slightly up and do ...

Extract JSON Data from Nested Object

I'm currently struggling with parsing JSON data from an object within an object using a Node.js script. Here's the JSON Object: { "Item":{ "job_change_request":"task0020764", "id":"a156fc4e-e8d4-424f-a792-0c8cf8e3ca46", ...

When the enter key is pressed, the anchor tag does not function properly after setting the tabindex value to "0" for the surrounding div element

Having an issue with Safari not focusing on my anchor element. I added tabindex="0" around the div to address this, but now the link doesn't work when pressing enter in any browser. Am I missing something here? <div class="used__button&quo ...

Using Vue to bind a class attribute with multiple Tailwind classes

I am attempting to associate an attribute and multiple tailwind classes with an HTML element. This is specifically for a tab menu where the goal is to dynamically display the title of the "active" tab and apply additional tailwind classes to modify the app ...

In node.js, the global variable fails to update within a while loop

I need to store data in an array every 5 seconds. My initial approach was: setInterval(function() { data.push({ price: getCurrentPrice(), time: moment().format() }) }, 5000); However, after running for exactly half an hour, the s ...

Show component depending on the lifecycle of another component

I recently encountered a problem with one of my custom components. I developed a "Chargement" Component (Loading in French) for a project I am currently working on. The component is a basic circular spinner with a dark background that indicates to the use ...

Every time I restart VSCode, I have to re-run the .zsh_profile command in order for the NVM packages to work properly

Many others have encountered a similar issue, but I'm struggling to resolve it. Every time I open VSCode, I find myself needing to run these commands in the terminal for npx, npm, and nvm to work: export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] ...

JavaScript encounters an Access Denied error when attempting to read data from a JSON file in

My code is experiencing issues on IE browser and Chrome, but works perfectly on FireFox. var currentPage = 1; var max = 0; var myList = []; var links = []; $.ajax({ cache: false, type : 'GET', crossDomain: true, ...

Tips for retrieving the ID of a dynamic page

In my Higher Order Component (HOC), I have set up a function that redirects the user to the login page if there is no token. My goal is to store the URL that the user intended to visit before being redirected and then push them back to that page. However, ...

Selecting multiple elements with the same attribute value using jQuery

I am looking to target specific DOM elements using jQuery. Below is the HTML code: <li> <span class="node> <span class="con"></span> <span class="check"></span> <img> <a title="high">abc&l ...

Oops! We encountered an internal issue: MongooseError: The operation `posts.insertOne()` has exceeded the buffering time limit of 100

Encountering an error when trying to post data to the Posts model upon clicking the post button: Internal error: MongooseError: Operation posts.insertOne() buffering timed out after 10000ms My setup includes a local MongoDB and Next.js 14 with app router. ...

Adjusting image size to fit divs depending on orientation

I am currently working on a project where I need images to fill a div while still maintaining their aspect ratio. To achieve this, I am utilizing jQuery to determine if the images are portrait or landscape, and adjusting the width or height accordingly. H ...

Ways to guide user after logging out

My Angular front end includes the following code in app.js to handle user logout: .when('/logout', { templateUrl: 'mysite/views/logout.html', resolve: { authenticated: ['djangoAuth', function(djangoAuth){ return ...

How can we capture the current row's value for later retrieval?

Using datatables to display data from a mySQL database, I am looking to extract the current row's value and present it in a modal for editing. This is how the data is integrated into Datatable: $(document).ready(function() { $(' ...

Looping through the ajax data to populate ion-item elements

I am currently working on a loop that retrieves user IDs, names, etc. from a JSON file. I am trying to display this data in a list view within an Ionic framework. When I simply use direct alerts in JavaScript, the users are displayed correctly, but when I ...

Can an AJAX upload progress bar be implemented in Internet Explorer without using Flash?

I've been searching for solutions to upload files without using flash, but all of them either require flash or lack a progress bar on IE (7-8). I couldn't find any mention of an "progress" event in the MSDN documentation for XMLHTTPRequest. Is i ...

Get the value of a specific option within a React-bootstrap Form component

A special Form has been created to retrieve the selected value from an option. import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; import { useState } from "react"; export default function Cu ...

Understanding special characters within a URL

Here is a URL example: postgres://someuser:pas#%w#@rd-some-db.cgosdsd8op.us-east-1.rds.amazonaws.com:5432 This URL is being parsed using the following code snippet: const url = require('url'); const { hostname: host, port, auth, path } = url.par ...