Having trouble getting the lightning to cooperate

Currently, I am diving into three.js and encountered a baffling issue. I successfully created a cube that responds to the A and D keys for rotation, but I am struggling to implement proper lighting. Despite referencing several examples and attempting to replicate them, the lighting feature refuses to work. Is there a glaring mistake that I am overlooking?

let scene = new THREE.Scene();
scene.background = new THREE.Color(0xf0f0f0);
let camera = new THREE.PerspectiveCamera(75, window.innerWidth / 
window.innerHeight, 0.1, 1000);
scene.add(camera);

//lightning
let light = new THREE.DirectionalLight(0xffffff, 1.0);
let lightAmbient = new THREE.AmbientLight(0x404040);
light.position.set(3, 0, 0).normalize();
scene.add(light, lightAmbient);

let renderer = new THREE.WebGLRenderer();
renderer.setSize(800, 600);
document.body.appendChild(renderer.domElement);

let geometry = new THREE.BoxGeometry(1, 1, 1);
let material = new THREE.MeshBasicMaterial({color: 0x539cef});
let cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 3;

let left = false;
let right = false;
cube.rotation.x += 0.5;

function animate() {
    document.addEventListener('keydown', event => {
        if(event.keyCode === 65) {
            left = true;
        }
        if(event.keyCode === 68) {
            right = true;
        }
    });
    document.addEventListener('keyup', event => {
        left = right = 0;
    })

    requestAnimationFrame(animate);
    if(left) {
        cube.rotation.y -= 0.05;
    } else if(right) {
        cube.rotation.y += 0.05;
    }
    renderer.render(scene, camera);
}

animate();
body { margin: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/95/three.min.js"></script>

Answer №1

A great tip is to attach directional light to the camera instead of the scene and opt for materials such as THREE.MeshLambertMaterial(), THREE.MeshPhongMaterial(), or THREE.MeshStandardMaterial().

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

Tips for modifying a particular element within a class?

I am seeking guidance on how to modify a specific class attribute in CSS/JS/JQuery when hovering over a different element. Here is an example: <h1 class="result">Lorium</h1> <h1 class="result">Ipsum</h1> <h1 class="result">Do ...

Using jQuery to toggle CSS properties

I'm having trouble switching between a CSS column layout and a normal layout for a div element with the ID 'article'. The jQuery script I wrote doesn't seem to work properly, as the entire thing disappears. Can anyone advise me on how t ...

Would it be better to lock a variable stored in req.session, or opt for a massive global variable instead?

As I delve into creating a game using node.js, the premise is sending units on missions and waiting for their return. The challenge lies in ensuring that the same unit cannot be sent on two different missions simultaneously, nor can two sets of units be di ...

Extract the data from a dynamically loaded AJAX page

What is the best way to retrieve the values from the form located in add.php? Add.php is a basic file that contains a single form. The submission process is handled by the code snippet below: var $addGroup = $('<div></div>') .load(&a ...

Can you build and run a production-ready Vue application on your local system?

After running the npm run build command in my vue project, I placed the dist folder in C:\xampp\htdocs\ and launched the apache server to test the app on my local machine. However, when I try to access http://localhost/dist/index.html in my ...

Using JQuery to extract the unique identifiers of nodes within a tree view format for the purpose of storing data according to these identifiers

Using Angular to display data in the view, I have a sample code here. When a specific age group category is clicked, I want to populate a form with data and save the entire dataset, including the parent node IDs. I am facing an issue with fetching the pa ...

Calculate averages of an array and show them when the page loads using Vue

In my coding project, there is an array named products that follows this specific structure: { "_id": "150", "name": "Milk", "description": "Skimmed", "price": "10", "ratings": [ ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

Different ways to maintain the original syntax highlighting colors in JavaScript console

Upon closer inspection near the green arrows, you can see that the default console.log function colorizes values based on their type, distinguishing between string and number. https://i.sstatic.net/MtO8l.png In contrast, highlighted near the red arrows i ...

Returning the user to the previous page after successfully submitting a web form on the current page in a .NET environment

Is there a simple way on a .net website to navigate a user back to the previous page they were on before submitting a form without needing a complex breadcrumb system? For example, imagine moving from Page1.aspx to Page2.aspx, which contains a form. Upon f ...

Is it possible to change the inner html to null during an active ajax request?

My goal is to have two separate data.html files inserted into two different HTML files without needing a click event. I want the structure of my data.html files to remain consistent, while allowing the template of my website to change dynamically by callin ...

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Order objects in a JavaScript array

Recently, I came across a list of student data fetched from an API: const Studentdata = { "StudentName1": { "active": true, "gender": "male" }, "StudentName2": { "active": false, "gender": "male" }, "S ...

Developing with AngularJS: Implementing Asynchronous Data Loading

Whenever I call a function, I encounter a Cannot read property of undefined error message, even though the data is being displayed correctly. From my understanding so far, this issue arises due to the asynchronous loading of data by AngularJS, and using p ...

Is it possible to pass makeStyles as a prop in React components?

Within my component, I am using a prop named styling to apply inline styles. However, I would like to pass some predefined styles that I have written using the makeStyles function. The specific style I want to pass is detailed below: const useStyles = ma ...

Error 404: This page seems to have gone missing. Django and react-router

Struggling to integrate reactjs and react-router (1.x) with my Django project. I'm finding it challenging to make everything work together seamlessly. For more details, you can check out the project on GitHub: https://github.com/liondancer/django-che ...

Using Selenium to Retrieve HTML Content Between Two Tags

How can I extract the following data from the provided HTML using Selenium 4 and XPath in Python? Message names (e.g. Message 1), Received timestamp (e.g. Received: 214-2342-234), and the most challenging part: message text (e.g. This is message nr. 1 it ...

What could be causing "Unknown property" errors when using unicode property escapes?

The MDN website provides examples of matching patterns with unicode support, such as: const sentence = 'A ticket to 大阪 costs ¥2000 ...

Contrasting the lib and es directories

I am seeking clarity on my understanding. I am currently working with a npm package called reactstrap, which is located in the node_modules folder. Within this package, there are 4 folders: dist es lib src I understand that the src folder contains the s ...