PointLight of Threejs

PointLight of Threejs [The light point turns around the object 360°]

insert image description here

import * as THREE from "three";
import {
    
     OrbitControls } from "three/examples/jsm/controls/OrbitControls";
// 创建场景
const scene = new THREE.Scene();

// 创建透视相机
const camera = new THREE.PerspectiveCamera(
  45,
  window.innerWidth / window.innerHeight,
  1,
  1000
);
// 相机的位置决定是否能看到物体 以及看到物体的大小
camera.position.set(-3, 0, 20);
scene.add(camera);

const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

// 给场景所有物体添加默认的环境贴图
const geometry = new THREE.SphereGeometry(1);
const material = new THREE.MeshStandardMaterial();
const sphere = new THREE.Mesh( geometry, material );
// 物体投射阴影
sphere.castShadow = true
scene.add(sphere)


// 添加平面
const planeGeometry = new THREE.PlaneGeometry( 20, 20 );
const plane = new THREE.Mesh( planeGeometry, material );
plane.position.set(0, -1, 0)
plane.rotation.x = -Math.PI / 2;
// 平面接收阴影
plane.receiveShadow = true;
scene.add( plane );


// 环境光: 散光
const light = new THREE.AmbientLight( 0xffffff,0.5 ); // soft white light
scene.add( light );


const smallBox = new THREE.Mesh(
  new THREE.SphereGeometry(0.1),
  new THREE.MeshBasicMaterial({
    
    color: 0xff0000})  // 基础材质不受光照影响
)
smallBox.position.set(0,2,4)

// 平行光  一般需要设置方向
const pointLight = new THREE.PointLight( 0xff0000, 0.5 );
// pointLight.position.set(5, 10, 10)
// 让平行光产生阴影效果
pointLight.castShadow = true
// 光源添加到小球上
smallBox.add(pointLight)
scene.add( smallBox );


// 创建渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// 开启设置阴影贴图
renderer.shadowMap.enabled = true
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);

const clock = new THREE.Clock()
controls.update();
function animate() {
    
    
  let time = clock.getElapsedTime();
  // x、z  一个sin  一个 cos  就行  x:sin,z:cos   /  x:cos,z:sin
  // 说明xz是对角
  smallBox.position.z = Math.sin(time) * 3
  smallBox.position.x = Math.cos(time) * 5
  // smallBox.position.y = 2 + Math.sin(time * 3)
  requestAnimationFrame(animate);
  controls.update();

  // 轨道控制器需要每一帧都在渲染
  renderer.render(scene, camera);
}
animate();























window.addEventListener("resize", () => {
    
    
  camera.aspect = window.innerWidth / window.innerHeight;
  // 更新摄像机投影矩阵。在任何参数被改变以后必须被调用
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setPixelRatio(window.devicePixelRatio);
});

Guess you like

Origin blog.csdn.net/weixin_44224921/article/details/129886084