码迷,mamicode.com
首页 > Web开发 > 详细

为THREEJS场景添加光影效果

时间:2015-04-30 12:20:05      阅读:1177      评论:0      收藏:0      [点我收藏+]

标签:

添加光影效果主要用到的代码如下:

//使渲染器支持阴影贴图

THREE.Render.shadowMapEnabled= true;

//设置灯光阴影属性

//设置灯光生成阴影

THREE.Light.castShadow= true;

//如果是调试状态,还可以把灯光的调试帮助框显示出来

THREE.Light.shadowCameraVisible= true;

//设置阴影贴图质量

THREE.Light.shadowMapWidth = THREE.Light.shadowMapHeight = 1024*4;

//设置模型属性

//设置物体生成阴影

THREE.Mesh.castShadow = true;
//设置物体接收阴影,即其它物体的阴影可以显示在该物体上

THREE.Mesh.receiveShadow= true;

完整的测试代码如下:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<script src="ThreeJS/build/three.js"></script>
<script src="ThreeJS/examples/js/controls/OrbitControls.js"></script>
<script src="ThreeJS/examples/js/loaders/OBJMTLLoader.js"></script>
<script src="ThreeJS/examples/js/loaders/MTLLoader.js"></script>
<script>
    var _scene,_camera,_control,_render,_ambient,_spotLight;
    Init();
    Animate();
    function Init()
    {
        _scene = new THREE.Scene();

        _camera = new THREE.PerspectiveCamera(45,window.innerWidth/window.innerHeight,0.1,2000);
        _camera.position.z = 50;

        _render = new THREE.WebGLRenderer();
        //设置渲染器大小
        _render.setSize(window.innerWidth,window.innerHeight);
        //设置渲染器阴影可用
        _render.shadowMapEnabled = true;
        document.body.appendChild(_render.domElement);

        //场景控制器,用以控制场景中的摄相机,方便观察场景
        _control = new THREE.OrbitControls(_camera,_render.domElement);

        //添加环境光
        _ambient = new THREE.AmbientLight(0xffffff);
        _scene.add(_ambient);
        //灯光属性
        _spotLight = new THREE.SpotLight(0xffffff);
        _spotLight.castShadow = true;
        _spotLight.shadowCameraVisible = true;
        _spotLight.position.set(100,100,100);
        //设置阴影贴图精度
        _spotLight.shadowMapWidth = _spotLight.shadowMapHeight = 1024*4;
        _scene.add(_spotLight);
        //加载模型
        LoadModel();
    }
    function Animate()
    {
        requestAnimationFrame(Animate);
        Render();
    }
    function Render()
    {
        //更新摄相机角度
        _control.update();
        _render.render(_scene,_camera);
    }
    function LoadModel()
    {
        //调用OBJMTLLoader加载模型
        var loader = new THREE.OBJMTLLoader();
        loader.load(‘Model/tc_tm/tc.obj‘,‘Model/tc_tm/tc.mtl‘,
        function(obj)
        {
            //traverse:回调,该模型以及所有子模型均执行该函数
            //相当于遍历obj的children数组
            obj.traverse(function(child)
            {
                if (child instanceof THREE.Mesh)
                {
                    //设置模型生成阴影并接收阴影
                    child.castShadow = true;
                    child.receiveShadow = true;
                }
            });
            _scene.add(obj);
        });
    }
</script>
</body>
</html>

效果如下图所示:

远观:

技术分享

近看:

技术分享

为THREEJS场景添加光影效果

标签:

原文地址:http://www.cnblogs.com/cll131421/p/4468466.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!