nonocast / me

记录和分享技术的博客
http://nonocast.cn
MIT License
20 stars 0 forks source link

学习 three.js (Part 2: Light) #324

Open nonocast opened 2 weeks ago

nonocast commented 2 weeks ago
import * as THREE from "three";

const scene = new THREE.Scene();

// const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
// fov (视角): 相机的视角(单位: 度)。控制视野的大小,值越大视野越宽。
// aspect (纵横比): 相机的纵横比。通常是窗口的宽度除以高度。
// near (近截面): 相机的近截面距离。控制从相机到近截面的距离。
// far (远截面): 相机的远截面距离。控制从相机到远截面的距离。
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

// three.js中,z轴的正方向是朝向屏幕外为正, x轴水平向右为正,y轴垂直向上为正
camera.position.set(10, 10, 10);
camera.lookAt(0, 0, 0);

const renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true; 
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const light = new THREE.PointLight(0xffffff, 300, 100);
light.position.set(10, 10, 10);
light.lookAt(0, 0, 0);
scene.add(light);

// 创建一个立方体
const geometry = new THREE.BoxGeometry(3, 3, 3);
const material = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const cube = new THREE.Mesh(geometry, material);
cube.position.y = 1.5;
scene.add(cube);

// 创建一个地面
const planeGeometry = new THREE.PlaneGeometry(100, 100);
const planeMaterial = new THREE.MeshStandardMaterial({ color: 0xffffff });
const plane = new THREE.Mesh(planeGeometry, planeMaterial);
plane.receiveShadow = false;
plane.rotation.x = - Math.PI / 2;
plane.position.set(0, 0, 0);
scene.add(plane);

renderer.render(scene, camera);
Screenshot 2024-09-08 at 00 50 38

注意:

  1. threejs采用右手左边系,x轴水平向右为正,y轴垂直向上为正,z轴向屏幕外为正
  2. plane加进scene默认是yz面,如果要水平则需要旋转-1/2pi,要注意 normal (法线)