Three.js Lighting Not Working – Object is fully lit

I’m following along this three.js tutorial: https://www.youtube.com/watch?v=_OwJV2xL8M8

So far, my site is meant to show a canvas with a green sphere in the middle, with a point light on top of it. However, my point light isn’t working, and my sphere is evenly lit. I’ve initialized my project using vite.

Here’s my HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="icon" type="image/svg+xml" href="/vite.svg">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite Project</title>
</head>
<body>
    <canvas class="webgl"></canvas>
    <script type="module" src="/main.js"></script>
</body>
</html>

And here’s my javascript code:

import * as THREE from 'three'

const scene = new THREE.Scene()

const geometry = new THREE.SphereGeometry(3, 64, 64);
const material = new THREE.MeshBasicMaterial({
    color: '#c0ff83'
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

const light = new THREE.PointLight(0xfcfcff, 4, 60);
light.position.set(0, 10, 10);
scene.add(light);

const camera = new THREE.PerspectiveCamera(45, 800 / 600); // updated
camera.position.z = 16;
scene.add(camera);

const canvas = document.querySelector(".webgl");
const renderer = new THREE.WebGLRenderer({canvas});
renderer.setSize(800, 600);
renderer.render(scene, camera);

I tried commenting out the lighting code but still got the same result.

My errors are below. Any ideas?

Errors

>Solution :

MeshBasicMaterial is a so called "unlint" material. That means it does not react on lights. Try it with a lit material like MeshLambertMaterial or MeshPhongMaterial.

const scene = new THREE.Scene()

const geometry = new THREE.SphereGeometry(3, 64, 64);
const material = new THREE.MeshLambertMaterial({color: '#c0ff83'});

const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

const light = new THREE.PointLight(0xfcfcff);
light.position.set(0, 10, 10);
scene.add(light);

const camera = new THREE.PerspectiveCamera(45,  window.innerWidth / window.innerHeight); // updated
camera.position.z = 16;
scene.add(camera);

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild(renderer.domElement)

renderer.render(scene, camera);
body {
      margin: 0;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.148/build/three.min.js"></script>

Leave a Reply