three.js弹跳的小球加阴影
直接上代码,然后再对代码做解释,效果图在最后面。
import './style.css'
import * as THREE from 'three'
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
let scene = new THREE.Scene()
let camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
scene.add(camera)
//plane
const planeGeometry = new THREE.PlaneGeometry(40, 40)
const planeMaterial = new THREE.MeshStandardMaterial({side: THREE.DoubleSide})
let plane = new THREE.Mesh(planeGeometry, planeMaterial)
// 旋转90度
plane.rotation.x = Math.PI / 2
//设置接收阴影
plane.receiveShadow = true
scene.add(plane)
//sphere
let sphereBufferGeometry = new THREE.SphereBufferGeometry(2, 30, 30);
let sphereMaterial = new THREE.MeshStandardMaterial({color: "#8776af"})
let sphere = new THREE.Mesh(sphereBufferGeometry, sphereMaterial)
sphere.position.set(10, 0, -10)
sphere.castShadow = true
scene.add(sphere)
// 聚光灯光源
let spotLight = new THREE.SpotLight("#fff", 1.5);
spotLight.position.set(20, 20, -20)
spotLight.castShadow = true
spotLight.shadow.mapSize = new THREE.Vector2(1024,1024)
spotLight.shadow.camera.far = 200
spotLight.shadow.camera.near = 0.1
scene.add(spotLight)
let renderer = new THREE.WebGLRenderer({
// 抗锯齿
antialias:true
})
renderer.setSize(window.innerWidth, window.innerHeight)
// 开启阴影渲染
renderer.shadowMap.enabled = true
document.body.appendChild(renderer.domElement)
// 轨道控制器
const orbitControls = new OrbitControls(camera, renderer.domElement);
// 阻尼
orbitControls.enableDamping = true
let clock = new THREE.Clock()
function render() {
let time = clock.getElapsedTime();
sphere.position.y = 2 + 10 * Math.abs(Math.sin(time))
orbitControls.update()
renderer.render(scene, camera)
requestAnimationFrame(render)
}
camera.position.set(30, 30, 0)
camera.lookAt(scene.position)
render()
style.css只是清除浏览器的一些默认样式。
首先是新建一个场景,还有摄像机,把摄像机放入场景中。然后创建一个平面,后面小球就在这个平面上来回弹跳,这里的材质使用MeshStandardMaterial,这个材质对光照有反应,可以接收阴影。把平面沿着x平面旋转90度。
然后添加小球,给小球设置一个颜色,然后对小球的初始位置做一些调整。
然后添加一个灯光。
小球弹跳的逻辑代码在render函数里,就是下面这两行
let time = clock.getElapsedTime();
sphere.position.y = 2 + 10 * Math.abs(Math.sin(time))
第一行代码就是获取间隔时间,第二行代码是改变小球y轴坐标的位置,2是小球的半径 ,加一个2可以使小球刚好落在平面上,然后根据时间生成三角函数,这样小球就会来回的跳动了。
效果如下:
three.js弹跳的小球加阴影
https://www.zhaojun.inkhttps://www.zhaojun.ink/archives/threejs-dan-tiao-de-xiao-qiu-jia-yin-ying