three.js 03-02 之 PointLight 光源

59 篇文章 2 订阅
59 篇文章 6 订阅

    前一篇,我们对 AmbientLight 环境光做了一个简单的介绍。本篇我们来介绍 three.js 中的另一种光源 PointLight(点光源)。照例我们先来一个完整示例:

<!DOCTYPE html>
<html>
<head>
    <title>示例 03.02 - 点光源</title>
	<script src="../build/three.js"></script>
	<script src="../build/js/controls/OrbitControls.js"></script>
	<script src="../build/js/libs/stats.min.js"></script>
	<script src="../build/js/libs/dat.gui.min.js"></script>
	<script src="../jquery/jquery-3.2.1.min.js"></script>
    <style>
        body {
            /* 设置 margin 为 0,并且 overflow 为 hidden,来完成页面样式 */
            margin: 0;
            overflow: hidden;
        }
		/* 统计对象样式 */
		#Stats-output {
			position: absolute;
			left: 0px;
			top: 0px;
		}
    </style>
</head>
<body>

<!-- 用于 WebGL 输出的 Div -->
<div id="WebGL-output"></div>
<!-- 用于统计 FPS 输出的 Div -->
<div id="Stats-output"></div>

<!-- 运行 Three.js 示例的 Javascript 代码 -->
<script type="text/javascript">

	var scene;
	var camera;
	var render;
	var controls;
	var stats;
	var guiControls;
	
	var cube;
	var sphere;
	var pointLight;
	var lightMesh;

    // 当所有元素加载完毕后,就执行我们 Three.js 相关的东西
    $(function() {
		stats = initStats();
		
		scene = new THREE.Scene();
		camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000); // 2147483647
		camera.position.set(-30, 40, 30);
		render = new THREE.WebGLRenderer( {antialias: true} ); // antialias 抗锯齿
		render.setSize(window.innerWidth, window.innerHeight);
		render.setClearColor(0xEEEEEE);
		//render.shadowMap.enabled = true; // 允许阴影投射
		$('#WebGL-output')[0].appendChild(render.domElement);
		window.addEventListener('resize', onWindowResize, false);
		var target = new THREE.Vector3(scene.position.x, scene.position.y ,scene.position.z);
		controls = new THREE.OrbitControls(camera, render.domElement);
		controls.target = target;
		camera.lookAt(target);
		
		scene.add(new THREE.AxisHelper(20));// 加入坐标轴
		
		// 加入一个平面(带线框效果)
		var planeGeometry = new THREE.PlaneGeometry(60, 20, 1, 1);
		var planeMaterials = [
			new THREE.MeshPhongMaterial( {color: 0xFFFFFF} ),
			new THREE.MeshBasicMaterial( {color: 0xFFFFFF, wireframe: true, transparent: true, opacity: 0.5} )
		];
		var plane = THREE.SceneUtils.createMultiMaterialObject(planeGeometry, planeMaterials);
		plane.rotation.x = -0.5 * Math.PI; // 沿着 X轴旋转-90°
		plane.position.x = 15; // 沿着 x轴右移 15个单位
		plane.position.y = 0; // y轴为 0
		plane.position.z = 0; // z轴为 0
		plane.children[0].receiveShadow = true; // 非线框几何平面接收阴影
		scene.add(plane);
		
		// 加入一个立方体
		var cubeGeometry = new THREE.BoxGeometry(4, 4, 4);
		var cubeMaterial = new THREE.MeshLambertMaterial( {color: 0xFF7777} );
		cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
		cube.position.x = -4;
		cube.position.y = 3;
		cube.position.z = 0;
		cube.castShadow = true; // 立方体投射阴影
		scene.add(cube);
		
		// 加入一个球体
		var sphereGeometry = new THREE.SphereGeometry(4, 20, 20);
		var sphereMaterial = new THREE.MeshLambertMaterial( {color: 0x7777FF} );
		sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
		sphere.position.x = 20;
		sphere.position.y = 4;
		sphere.position.z = 2;
		sphere.castShadow = true; // 球体投射阴影
		scene.add(sphere);
		
		// 加入一个环境光源
		var ambientLight = new THREE.AmbientLight(0x0c0c0c);
		scene.add(ambientLight);
		
		// 加入一个小球体来表示点光源位置
		sphereGeometry = new THREE.SphereGeometry(0.2, 20, 20);
		sphereMaterial = new THREE.MeshBasicMaterial( {color: 0xac6c25} );
		lightMesh = new THREE.Mesh(sphereGeometry, sphereMaterial);
		// 加入一个点光源:color 颜色, intensity 强度, distance 距离, decay 衰减
		pointLight = new THREE.PointLight( 0xccffcc, 1, 100, 2);
		pointLight.position.set(3, 5, 3);
		pointLight.castShadow = true; // 光源产生阴影
		pointLight.shadow.mapSize.width = 2048; // 必须是 2的幂,默认值为 512
		pointLight.shadow.mapSize.height = 2048; // 必须是 2的幂,默认值为 512
		pointLight.add(lightMesh);
		scene.add(pointLight);
		
		/** 用来保存那些需要修改的变量 */
		guiControls = new function() {
			this.rotationSpeed = 0.02;
			this.bouncingSpeed = 0.04;
			this.ambientColor = '#0c0c0c';
			this.pointColor = '#ccffcc';
			this.intensity = 1;
			this.distance = 100;
			this.decay = 2;
			this.disableSpotLight = false;
		}
		
		/** 定义 dat.GUI 对象,并绑定 guiControls 的有关属性 */
		var gui = new dat.GUI();
		gui.addColor(guiControls, 'ambientColor').onChange( function(e) {
			ambientLight.color = new THREE.Color(e);
		});
		gui.addColor(guiControls, 'pointColor').onChange( function(e) {
			pointLight.color = new THREE.Color(e);
		});
		gui.add(guiControls, 'intensity', 0, 3).onChange( function(e) {
			pointLight.intensity = e;
		});
		gui.add(guiControls, 'distance', 0, 100).onChange( function(e) {
			pointLight.distance = e;
		});
		gui.add(guiControls, 'decay', 0, 30).onChange( function(e) {
			pointLight.decay = e;
		});
		gui.add(guiControls, 'disableSpotLight').onChange(function(e){
			pointLight.visible = !e;
		});
		
		renderScene();
    });
	
	/** 渲染场景 */
	function renderScene() {
		stats.update();
		rotateCube(); // 旋转立方体
		bounceSphere(); // 弹跳球体
		moveLight(); // 移动点光源及其小球
		requestAnimationFrame(renderScene);
		render.render(scene, camera);
	}
	
	/** 初始化 stats 统计对象 */
	function initStats() {
		stats = new Stats();
		stats.setMode(0); // 0 为监测 FPS;1 为监测渲染时间
		$('#Stats-output').append(stats.domElement);
		return stats;
	}
	
	/** 当浏览器窗口大小变化时触发 */
	function onWindowResize() {
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();
		render.setSize(window.innerWidth, window.innerHeight);
	}
	
	/** 转动立方体 */
	function rotateCube() {
		cube.rotation.x += guiControls.rotationSpeed;
		cube.rotation.y += guiControls.rotationSpeed;
		cube.rotation.z += guiControls.rotationSpeed;
	}
	
	/** 弹跳球体 */
	var step = 0;
	function bounceSphere() {
		step += guiControls.bouncingSpeed;
		sphere.position.x = 20 + (10 * Math.cos(step));
		sphere.position.y = 2 + (10 * Math.abs(Math.sin(step)));
	}
	
	/** 移动点光源及其小球 */
	var invert = 1;
	var phase = 0;
	function moveLight() {
		if (phase > 2 * Math.PI) {
			//debugger;
			invert = invert * -1;
			phase -= 2 * Math.PI;
		} else {
			phase += guiControls.rotationSpeed;
		}
		pointLight.position.x = 14 * (Math.cos(phase));
		pointLight.position.z = 7 * (Math.sin(phase));
		pointLight.position.y = 5;
		//console.log('x:%f, z:%f, phase', pointLight.position.x, pointLight.position.z, phase);
		if (invert < 0) {
			var pivot = 14;
			pointLight.position.x = (invert * (pointLight.position.x - pivot)) + pivot;
		}
	}

</script>
</body>
</html>
    在 three.js 库中 PointLight 是一种单点发光,照射所有方向的光源。夜空中的照明弹就是一个很好的点光源例子。在上面这个例子中我们会看到一个点光源正在绕场景移动。为了能清楚看到点光源的位置,我们利用 PointLight.add(object) 函数为其添加了一个橙色的小球(Sphere 对象)随着光源的移动而移动。场景中的红色立方体和蓝色球体被照亮了。由于点光源会朝所有的方向发射光线,在这种情况下如果开启阴影的话会对计算机 GPU 产生沉重的负担。因此,本示例中注销了以下这句代码:

// render.shadowMap.enabled = true; // 允许阴影投射
    生成一个点光源比较简单,我们所要做的只是设置光照颜色、光照强度、光照距离等即可,具体可以设置的主要几个属性如下表所示:
属性描述
color (光照颜色)光源的颜色
intensity (光照强度)光照的强度。默认值是 1
distance (光照距离)光源照射的距离。默认值是 0,表示光照永不停止
decay (衰减度)光源的照射随着距离的增加而衰减的程度。默认值是 1,推荐设置值为 2
position (位置)光源所在的位置
visible (是否可见)如果设置为 true,该光源就会打开;如果设置为 false,该光源就会关闭
在这个例子中,读者可以通过右上角的一些菜单来试验观察各种搭配所产生的效果。此处建议尝试以下几种搭配:

  1. 分别将 intensity 设为 0、1 和 2 并观察效果变化;
  2. 把 intensity 设为 3,distance 设为 14 并观察效果变化;

在第二种搭配中,光照的强度(intensity)在距离(distance)为 14 的范围内慢慢降到 0。所以当光源移动到红色立方体一侧时,蓝色的球体几乎就看不清了。

未完待续···

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值