What steps can I take to ensure that the airplane is able to cast shadows?

I'm trying to make the plane receive a shadow from the sphere, but I seem to be making a mistake somewhere along the way. Does anyone have any ideas on how to fix it?

//.................SETUP................//
import {
    WebGLRenderer,
    PerspectiveCamera,
    Scene,
    BoxGeometry,
    MeshBasicMaterial,
    Mesh,
    Group,
    PlaneGeometry,
    AxesHelper,
    GridHelper,
    DoubleSide,
    DirectionalLight,
    AmbientLight,
    MeshStandardMaterial,
    DirectionalLightHelper,
    Fog,
    TextureLoader,
    CubeTextureLoader,
    SphereGeometry,
} from './three.module.js';
import { OrbitControls } from './q.js';
//................PROGRAM...............//
var renderer, camera, scene, light, light1, geometry, material, mesh;
// renderer
renderer = new WebGLRenderer({canvas:
document.getElementById('Canvas'), antialias: true, alfa: true});
  //alfa: true makes empty pixels in the canvas show underlying html content so that if there is an image under an empty canvas element, you can still see the image.
renderer.setClearColor(0x555555);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enable = true; 
// camera
camera = new PerspectiveCamera(35, window.innerWidth / 
window.innerHeight, 0.1, 6000);
camera.position.set(0, 0, 100);
camera.lookAt(0, 0, 0);
//controls
var orbitcontrol = new OrbitControls(camera, renderer.domElement)
//scene
scene = new Scene();
//lights
//var ambientlight = new AmbientLight(0x333333);
//scene.add(ambientlight);
var sun = new DirectionalLight(0xffffff, 0.8);
sun.castShadow = true;
scene.add(sun);
sun.position.set(0, 40, 0);
//fog
//scene.fog = new Fog(0xffffff, 0, 200); 
//helpers
var gridhelper = new GridHelper(10, 10);
scene.add(gridhelper);
var axishelper = new AxesHelper(3);
scene.add(axishelper);
var directionallighthelper = new DirectionalLightHelper(sun, 10, 0xff0000);
scene.add(directionallighthelper);
//material loaders
var bildimport = new TextureLoader().load('a.jpg');
var bildimport2 = new TextureLoader().load('träd.jpg');
var textureLoader = new TextureLoader();
scene.background = textureLoader.load('a.jpg');
//objects
  //sphere
  var geometrySphere = new SphereGeometry(10, 15);
  var materialSphere = new MeshStandardMaterial({
    color: 0xffff00f,
    flatShading: true, 
    //wireframe: true, 
  });
  var meshSphere = new Mesh(geometrySphere, materialSphere);
  scene.add(meshSphere);
  meshSphere.position.set(0,20,0);
  meshSphere.castShadow = true;
  meshSphere.receiveShadow = true;
  //cube
geometry = new BoxGeometry(1, 1, 1);
var alt_material = [
  new MeshBasicMaterial({map: bildimport2}),
  new MeshBasicMaterial({map: bildimport}),
  new MeshBasicMaterial({map: bildimport2}),
  new MeshBasicMaterial({map: bildimport}),
  new MeshBasicMaterial({map: bildimport2}),
  new MeshBasicMaterial({map: bildimport}),
];
material = new MeshStandardMaterial({
    color: 0xff0000,
    map: bildimport2,
});
mesh = new Mesh(geometry, alt_material);
mesh.position.set(0, 50, 0);
mesh.castShadow = true;
scene.add(mesh);
  //plane
var geometry2 = new PlaneGeometry(50, 50); 
var material2 = new MeshStandardMaterial({
    color: 0xfff00,
    map: bildimport,
    side: DoubleSide,  // Makes the plane colored on both sides instead of just on the top.
});
var mesh2 = new Mesh(geometry2, material2);
mesh2.receiveShadow = true;
scene.add(mesh2);
mesh2.rotation.x = -0.5 * Math.PI;
//groups
//renderer loop 
requestAnimationFrame(render);
var i = 0;
var increase_of_i = 0.01;
function render() {
  mesh.rotation.x += 0.01;
  mesh.rotation.y += 0.01;
 // mesh.position.y = 100 * Math.abs(Math.sin(i));
  mesh.scale.x = 1 + Math.abs(Math.sin(2*i));
  mesh.scale.y = 1 + Math.abs(Math.sin(2*i));
  mesh.scale.z = 1 + Math.abs(Math.sin(2*i));
  i += increase_of_i;
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}

I'm trying to get the plane to receive a shadow from the sphere, but I seem to be making a mistake somewhere along the way. Does anyone have any ideas on how to fix it?

Answer №1

Your code has a small error - it should read renderer.shadowMap.enabled (the last letter d is missing).

In addition, you have neglected to set up the directional light's shadow which may be necessary. Typically, this involves adjusting the shadow camera's frustum so that it encompasses all 3D objects casting and receiving shadows. You can visually inspect the frustum using THREE.CameraHelper like this:

scene.add( new THREE.CameraHelper( sun.shadow.camera ) );

To configure the frustum, use the following settings:

sun.shadow.camera.top = 25;
sun.shadow.camera.bottom = - 25;
sun.shadow.camera.left = - 25;
sun.shadow.camera.right = 25;
sun.shadow.camera.near = 0.1;
sun.shadow.camera.far = 100;

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

Using Jquery and CSS to display or conceal table elements depending on viewport width

I am seeking advice for my issue. Here is the code snippet on JSFiddle. I have a list of models and corresponding values that vary across different categories. I have created a simple table to display this data. However, I need to alter the table structur ...

Jquery functions are failing to work in a fresh window

I am facing an issue with my project codes where I need to open a new window, display its contents, and then replace a specific div with some content. However, the JavaScript functions in the new window are not working. How can I enable JavaScript function ...

The operation cannot be found

I am completely new to javascript, so here is my situation: I'm attempting to integrate a reading-position-indicator into my WordPress theme. To achieve this, I placed a div right behind the footer, close to all the script tags, as the position bar s ...

A step-by-step guide on implementing img source binding in Vue.js

<template> <div class="text-center"> <h1 class="display-4 my-5"><mark>GIGS</mark></h1> <b-container fluid="lg"> <b-row class="mx-auto"> <b-col lg="4" class=" ...

Instructions for saving a binary file on the client using jQuery's .post function

I am working with a handler that has the following code: HttpRequest request = context.Request; HttpResponse response = context.Response; if (request["Type"] != null) { try { string resultFile = null; ...

Bring in an HTML page into a DIV element by utilizing .load with jQuery

I have a PHP function that generates and returns HTML content, and I want to display that content in a DIV when the page loads. Currently, I am attempting to do this by: <div id="myModal" class="reveal-modal" title="El Farol" data-animation="fade"> ...

Warning: The file or directory 'C:UsersNuwanstpackage.json' does not exist

Can someone help me with installing socket.io in my project located in the 3.chat folder? I'm encountering some warnings when running the command and it's not creating a node_modules directory. Any suggestions on how to resolve this? C:\Use ...

How to automatically select the first item in a populated dropdown list using Vue JS

My HTML select element is populated with options from a server, but when using v-model, it initially selects an empty option instead of the first one. I came across a solution on a post which suggests selecting the first option manually, but since the dat ...

What is the best approach to execute the jquery script exclusively on mobile devices?

I want to modify this code so that it only functions on mobile devices and is disabled on computers. How can I achieve this? <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <ul id="pri ...

Encountering error ORA-12514 when utilizing the node oracle-db npm package

At the moment, I am immersed in a project that relies on utilizing oracle for its backend. Following the instructions provided in this link, I successfully installed node-oracledb on my Mac using npm. The contents of my file are as follows: var oracledb = ...

Various perspectives within a state

I am facing an issue with my articledetail state when navigating to it: $state.go('articledetail', { 'article': article.itemNumber }); Within the articleDetail.html file, I want to display all subviews simultaneously: <div cla ...

I am unable to implement v-bind click within a v-for loop

While working with VueJS framework v-for, I encountered a problem when trying to loop through lists of items. Each item index was supposed to be assigned to a variable, but the v-bind click event wasn't being attached properly inside the v-for element ...

Displaying separate items onto a webpage based on their unique identifiers

Currently, I am in the process of developing a JavaScript web application that retrieves input from a user (specifically the name of a music artist) and then produces a list of related artists along with their most popular songs, all thanks to information ...

Tricks for preventing axios from caching in GET requests

I am utilizing axios in my React-Native application Firstly, I set up the headers function setupHeaders() { // After testing all three lines below, none of them worked axios.defaults.headers.common["Pragma"] = "no-cache"; axios.defaults.heade ...

Is it possible to determine if a selected date falls within the current week using JavaScript?

Currently facing an issue with JavaScript. I have multiple dates retrieved from a database, and I need to extract the date that falls within the current week. ...

adjusting the vertical axis scale on the Google Charts API

During my experimentation with setting the vertical axis scale in Google charts, I found that the automatic scaling was not satisfactory for comparing two results. I wanted both results to be on an equal scale for a fair comparison. Despite setting the ma ...

Combining Promise.all with the dependency of the first promise's response relying on the second promise

Currently, I am attempting to utilize Promise.all with the second promise being reliant on the response of the first promise. Below is my code snippet: let user = await userService.getByKey({ _id: params.userId }); let room = await matchService.findUserInR ...

Is it possible to use JavaScript to upload and manipulate multiple HTML files, replacing text within them to create new output HTML pages?

Is it possible to modify the following code to accept multiple files, process them, and then return the output? <html> <head> </head> <body> <div> <label for="text">Choose file</label> <inp ...

The Wordpress plugin's Ajax function is giving back a response value of zero

I'm facing an issue where I am attempting to send AJAX data to my wordpress table, but the response I receive from my PHP script is always a 0. This problem arises specifically on the admin side of things. Can anyone provide assistance? Furthermore, ...

Issues with Bootstrap Toggle Button functionality

I encountered a navbar error while working on my Django Project. After adding a few script tags, the navbar started to move down but did not return back to its original position. It worked fine before. By commenting out some script tags, it began to work a ...