ThreeJS投射阴影的使用

!!!
//开启渲染器的阴影计算

renderer.shadowMap.enabled=true

// 设置光照投射阴影开启

DirectionalLight.castShadow = true

// 设置物体投射阴影开启

cube.castShadow = true

// 设置地面接收物体阴影开启

cube2.receiveShadow=true


<script setup>

import * as THREE from "three";

// 导入轨道控制器

import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

// 1、创建场景

const scene = new THREE.Scene();

// 2、创建相机

const camera = new THREE.PerspectiveCamera(

  45,

  window.innerWidth / window.innerHeight,

  0.1,

  1000

);

// 设置相机位置

camera.position.set(2, 4, 15);

scene.add(camera);

// 初始化渲染器

const renderer = new THREE.WebGLRenderer();

// 设置渲染的尺寸大小

renderer.setSize(window.innerWidth, window.innerHeight);

// 将webgl渲染的canvas内容添加到body

document.body.appendChild(renderer.domElement);

// 创建轨道控制器

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

// 添加坐标轴辅助器

const axesHelper = new THREE.AxesHelper(5);

scene.add(axesHelper);

// 添加物体

// 创建几何体

const cubeGeometry = new THREE.SphereGeometry(1, 10, 10);

const material = new THREE.MeshStandardMaterial();

// 根据几何体和材质创建物体

const cube = new THREE.Mesh(cubeGeometry, material);

// 将几何体添加到场景中

let material2 = new THREE.MeshStandardMaterial()

const cubeGeometry2 = new THREE.PlaneGeometry(10,10)

const cube2 = new THREE.Mesh(cubeGeometry2,material2)

cube2.rotation.x=-Math.PI/2

cube2.position.y=-2

// 设置物体投射阴影开启

cube.castShadow = true

// 设置地面接收物体阴影开启

cube2.receiveShadow=true

scene.add(cube);

scene.add(cube2)

  //开启渲染器的阴影计算

  renderer.shadowMap.enabled=true

// 使用渲染器,通过相机将场景渲染进来

function render() {

  //如果后期需要控制器带有阻尼效果,或者自动旋转等效果,就需要加入controls.update()

  controls.update()

  renderer.render(scene, camera);

  //   渲染下一帧的时候就会调用render函数

  requestAnimationFrame(render);  


 

}

window.addEventListener('resize', onWindowResize, false);  

// 灯光

// 环境光

const light = new THREE.AmbientLight(0xffffff,0.5)

scene.add(light)

//直线光源

const DirectionalLight= new THREE.DirectionalLight(0xffffff,0.5)

DirectionalLight.position.set(10,10,10)

// 设置光照投射阴影开启

DirectionalLight.castShadow = true

scene.add(DirectionalLight)




 

// 定义窗口大小改变时的回调函数  

function onWindowResize() {  

  // 获取窗口大小  

  var width = window.innerWidth;  

  var height = window.innerHeight;  

  // 设置相机投影矩阵的宽高比和视口大小  

  camera.aspect = width / height;  

  camera.updateProjectionMatrix();  

  renderer.setSize(width, height);  

}

render();

</script>


 

<template></template>

<script>

export default {};

</script>

<style>

</style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值