Concerns have been raised regarding the lack of light and shadows being detected by THREE.BufferGeometry in JavaScript/th

I've been trying to generate terrain using noise functions, but I'm running into an issue where the BufferGeometry mesh isn't receiving any light from PointLight. When I switch to AmbientLight, the BufferGeometry is visible, but not with PointLight alone. Interestingly, the CubeGeometry next to it seems to work fine with both types of light. Additionally, I'm looking to have the terrain receive shadows as well. Is there a specific method I need to call on the mesh? What am I overlooking here?

https://jsfiddle.net/cbo8fx1s/

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://threejs.org/build/three.js"></script>
    <script>
      const scene = new THREE.Scene();
      const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      camera.position.z = 30;
      const renderer = new THREE.WebGLRenderer({antialias: true});

      // scene.add(new THREE.AmbientLight(0xffffff));

      window.addEventListener('resize', () => {
        camera.aspect = window.innerWidth / window.innerHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(window.innerWidth, window.innerHeight);
      });

      window.addEventListener('load', () => {
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        function animate() {
          requestAnimationFrame(animate);
          renderer.render(scene, camera);
        }
        animate();

        createScene();
      });

      function createScene() {
        (() => {
          const geometry = new THREE.BufferGeometry();
          // create a simple square shape. We duplicate the top left and bottom right
          // vertices because each vertex needs to appear once per triangle.
          const vertices = new Float32Array([
            -1.0, -1.0, 1.0,
            1.0, -1.0, 1.0,
            1.0, 1.0, 1.0,

            1.0, 1.0, 1.0,
            -1.0, 1.0, 1.0,
            -1.0, -1.0, 1.0
          ]);

          // itemSize = 3 because there are 3 values (components) per vertex
          geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));

          const material = new THREE.MeshStandardMaterial({color: 0xffffff});
          const mesh = new THREE.Mesh(geometry, material);
          mesh.receiveShadow = false;
          scene.add(mesh);
        })();

        (() => {
          const geometry = new THREE.CubeGeometry(10, 8, 3);
          const material = new THREE.MeshStandardMaterial({color: 0xffffff});
          const mesh = new THREE.Mesh(geometry, material);
          mesh.castShadow = true;
          mesh.receiveShadow = false;
          mesh.position.y = 10;
          scene.add(mesh);
        })();

        (() => {
          const light = new THREE.PointLight(0x00ff00);
          light.position.z = 500;
          light.position.y = 500;
          scene.add(light);

          const light2 = new THREE.PointLight(0xff0000);
          light2.position.z = 500;
          light2.position.x = 500;
          scene.add(light2);
        })();
      }
    </script>
    <style>
      body {
        background: #000;
        margin: 0;
        overflow: hidden;
      }
    </style>
  </head>
  <body>
  </body>
</html>

Answer №1

It appears that the geometry you are using does not have any normals. Without normals, lighting cannot properly shade the surfaces.

To rectify this issue, try adding the following code:

geometry.addAttribute('position', new THREE.BufferAttribute(vertices, 3));
geometry.computeVertexNormals()

By implementing these changes, your square should now display correctly.

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 incorporate multiple functions within a React button?

I need to implement a functionality where the startClick function is triggered on BackButton click before executing the dispatch (giveForm2PreviousStep(props.currentStep, props.goToStep)) method. How can this be achieved? Inquiry JS const Inquiry = props ...

The imported path is not found in Tsconfig

Hey there! I've been working on getting my project's imports to play nice with typescript import paths. Every time I encounter this error : Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'app' imported from dist/index.js It seems l ...

Discovering the minimum and maximum within an array containing objects

I am working with an array of objects that contain latitude and longitude points: var pts = [ { "X": 52.67528921580262, "Y": 8.373513221740723 }, { "X": 52.6759657545252, "Y": 8.374114036560059 }, { "X": 52.682574466310314, "Y": 8.372569084 ...

What is the best way to test speedy AJAX response times using Webdriver.io?

Currently, I am creating Cucumber.js tests using Webdriver.io. Everything seems to be going smoothly, but I'm encountering an issue with the mock server responding too quickly with AJAX. The "Loading..." message is not visible because the content load ...

Generating directives on the fly

I am relatively new to AngularJS and have a good understanding of the basics. My goal is to create a desktop interface where items are loaded dynamically from a database using $http. I have already developed a directive that displays a title and an icon fo ...

Iterating Through Array with Node JS Before Adding a New Property

There is a JSON input with data connected to a secondary model called Users. To process this, I need to iterate through listingData.Agents to extract the index ID and then use this ID to find the corresponding user. The challenge here is that due to asynch ...

What is the best way to forward a client to a different page using an Express post route?

I am currently working on a node/express web application where I have a button that, when clicked, transforms a <div> into a pdf, zips and secures the pdf with a password, sends it via email to the recipient, and finally generates a new page displayi ...

JavaScript: Creating a new entry in a key-value paired array

I am in the process of creating a dynamic menu for use with jQuery contextMenu. I have encountered an issue when trying to add a new element, as it keeps showing the error message 'undefined is not a function'. The menu functions correctly witho ...

What is the process for reversing the texture application direction on a CylinderGeometry object?

Is it possible to reverse the orientation of texture mapping on a CylinderGeometry object? var obj = new THREE.Mesh( new THREE.CylinderGeometry(20, 15, 1, 20), new THREE.MeshLambertMaterial({color: 0x000000}) //the material is later changed to the ...

Is there a way to choose the final JSON element using Javascript or Google Apps Script?

Imagine if I extracted this data from a constantly updating JSON file. [{ "data": { "member": "Feufoe, Robert", "project": "Random Event", }, "folder": null, "id": 1062110, "spam": null }, { "data": { "membe ...

Get a compressed folder from jszip containing a PDF file that is either empty or blank

I'm facing a challenge with my Vue app where I need to compress a group of PDF files in a folder using JSZip. While testing with just one file, the zip downloads successfully but when I try to open the PDF file inside it, the content appears blank. I ...

Error in JSON due to the presence of an unexpected token within the

I am facing a challenge with my PHP code, where I take a list of filenames or empty strings and store them in an array. This array is then converted to JSON and saved in a database successfully. However, the problem arises when this array is also stored wi ...

Vue: nesting components within components

Looking for a clever solution to create a nested component system with efficient rendering? Check out the code snippet below: custom-tab.vue (child component) <template> <slot></slot> </template> <script> export def ...

In React components, encountering "cannot read properties of undefined" error occurs, whereas it functions perfectly fine within the getStaticProps

I am currently in the process of setting up a blog using Node.js, React, and graphql. Despite being new to these technologies, including Java and Typescript, I am seeking assistance from anyone who may be able to help. My current roadblock involves display ...

Unable to retrieve image

I want to save a Discord user's profile picture on Replit, but even though it downloads successfully, the image is not displaying. Here is the code I am using: const request = require('request') const fs = require('fs') app.get(&qu ...

Uploading files with previews and no option to alter the image dimensions

I am having trouble with resizing an image preview before submitting it. Despite setting the width and height to 1px in both the div and image, it still displays at its normal dimensions. $(function() { var imagesPreview = function(input, placeToIns ...

Changing a JavaScript command into a text representation

Currently, I have an array stored in a variable as shown below: arr = [1, 2, 3] Is there a way to convert this array statement into a string like this? newArr = "arr = [1, 2, 3]" ...

The click event in jQuery is being blocked by the use of "display:none

Currently, I have implemented a search box feature with search suggestions: <input id="searchBar" /> <div id="searchSuggestion"></div> The searchSuggestion div is dynamically updated using jQuery ajax whenever an input is entered (imple ...

Switch from using getElementById to useRef in React components

There is a requirement to update a functional component that currently uses getElementById to instead utilize the useRef hook. The original code snippet is as follows: import React, { useState, useEffect, useRef } from 'react'; import { createPo ...

Utilizing the JSON result of an AWS MySQL query to display data as a DataTable on a webpage

I recently managed to link a website to a Lambda function via AWS API Gateway to execute a SQL query on an Aurora Serverless MySQL database. The JSON response is currently displayed in string form on the webpage, appearing like this: Since the columns mig ...