三个JS阴影不显示?

问题描述 投票:0回答:1

我用 Threejs 在我的网站上制作了一个交互式 3D 模型,除了阴影之外,所有东西都可以工作,我无法使阴影工作,我是三个 js 的新手,所以可能是我跳过了一些重要的部分。

这是我的JS代码:

import * as THREE from "https://cdn.skypack.dev/[email protected]/build/three.module.js";
import { OrbitControls } from "https://cdn.skypack.dev/[email protected]/examples/jsm/controls/OrbitControls.js";
import { GLTFLoader } from "https://cdn.skypack.dev/[email protected]/examples/jsm/loaders/GLTFLoader.js";

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

let mouseX = window.innerWidth / 2;
let mouseY = window.innerHeight / 2;
let object;
let controls;
let objToRender = 'dino';

const renderer = new THREE.WebGLRenderer({ alpha: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById("container3D").appendChild(renderer.domElement);

camera.position.z = objToRender === "dino" ? 4 : 500;

const topLight = new THREE.DirectionalLight(0xffffff, 3); 
topLight.position.set(-1.05307, 0.107503 , 4.52525 );
topLight.castShadow = true;
scene.add(topLight);

const ambientLight = new THREE.AmbientLight(0xFFFFFF, objToRender === "dino" ? 1 : 1);
scene.add(ambientLight);

renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap; 

const loader = new GLTFLoader();

loader.load(
    `models/${objToRender}/scene.gltf`,
    function (gltf) {
        object = gltf.scene;
        object.castShadow = true; 
        object.receiveShadow = true; 
        scene.add(object);
        animate(); 
    },
    function (xhr) {
        const percentage = (xhr.loaded / xhr.total * 100).toFixed(2);
        console.log(percentage + '% loaded');
        // Show loading progress somewhere in your UI
        document.getElementById("loadingProgress").innerText = `Loading: ${percentage}%`;
    },
    function (error) {
        console.error(error);
    }
);

if (objToRender === "dino") {
    controls = new OrbitControls(camera, renderer.domElement);
}

function animate() {
    requestAnimationFrame(animate);
    if (object && objToRender === "eye") {
        object.rotation.y = -3 + mouseX / window.innerWidth * 3;
        object.rotation.x = -1.2 + mouseY * 2.5 / window.innerHeight;
    }
    renderer.render(scene, camera);
}

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

document.onmousemove = (e) => {
    mouseX = e.clientX;
    mouseY = e.clientY;
};

这是我网站上的图片: enter image description here

我尝试向chatgpt寻求帮助,但他只给了我一些不起作用的修复。

javascript three.js shadow
1个回答
0
投票

您可以尝试的一种解决方案是制作对象的副本,而不是在副本上使用普通材质,而使用阴影材质。

© www.soinside.com 2019 - 2024. All rights reserved.