3.js - 物理引擎终极


javascript 复制代码
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import gsap from 'gsap' // 导入动画库
import * as dat from 'dat.gui' // 导入dat.gui

// 导入 cannon-es 引擎
import * as CANNON from 'cannon-es'

// --------------------------------------------------------------------------------

const scene = new THREE.Scene()

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 300)
camera.position.set(0, 0, 18)
scene.add(camera)

// -------------------------------------------------------------------------------

const cubeArr = []
const cubeWorldMaterial = new CANNON.Material('cube')

// 创建打击声音
const hitSound = new Audio('../public/assets/metalHit.mp3')

const createCube = () => {
	const cubeGeometry = new THREE.BoxGeometry(1, 1, 1)
	const cubeMaterial = new THREE.MeshStandardMaterial()
	const cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
	cube.castShadow = true
	scene.add(cube)
	
	// 创建物理世界,cube形状
	const cubeShape = new CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5))

	// 创建物理世界实体
	const cubeBody = new CANNON.Body({
		shape: cubeShape,
		position: new CANNON.Vec3(0, 0, 0),
		mass: 1, // 质量
		material: cubeWorldMaterial // 实体材质
	})

	cubeBody.applyLocalForce(
		new CANNON.Vec3(300, 0, 0), // 添加的力的大小和方向
		new CANNON.Vec3(0, 0, 0) // 施加的力,所在位置
	)

	// 将物体,添加到,物理世界
	world.addBody(cubeBody)

	// 添加监听碰撞事件
	const hitEvent = e => {
		// 获取碰撞强度
		const impactStrength = e.contact.getImpactVelocityAlongNormal()
		// console.log('impactStrength=', impactStrength)
		if (impactStrength > 2) {
			hitSound.currentTime = 0 // 重新播放
			hitSound.volume = impactStrength / 12
			hitSound.play()
		}
	}

	cubeBody.addEventListener('collide', hitEvent)
	cubeArr.push({
		mesh: cube,
		body: cubeBody
	})
}

window.addEventListener('click', createCube)

// -------------------------------------------------------------------------------

// 创建平面
const floor = new THREE.Mesh(new THREE.PlaneGeometry(20, 20), new THREE.MeshStandardMaterial())
floor.position.set(0, -5, 0)
floor.rotation.x = -Math.PI / 2
floor.receiveShadow = true // 接受别的物体的阴影
scene.add(floor)

`创建物理世界`
const world = new CANNON.World()
`设置物理世界的重力,重力被设置为仅在Y轴(竖直向下)上有作用,大小为-9.8(模拟地球表面的重力加速度)`
world.gravity.set(0, -9.8, 0)

// 创建 - 物理地面
const floorShape = new CANNON.Plane()
const floorBody = new CANNON.Body()
const floorMaterial = new CANNON.Material('floor')
floorBody.material = floorMaterial

  `当质量为0时,可以使物体保持不动
    这里,`floorBody`作为地面,不能动,
    所以,把它的质量设置为0,就行了 `
floorBody.mass = 0
floorBody.addShape(floorShape)
// 地面的位置
floorBody.position.set(0, -5, 0)
// 旋转地面的位置,围绕X轴(CANNON.Vec3(1, 0, 0))旋转了 -Math.PI / 2(即 90 度)
floorBody.quaternion.setFromAxisAngle(new CANNON.Vec3(1, 0, 0), -Math.PI / 2)
world.addBody(floorBody)

`设置,2种材质的碰撞参数`
const defaultContactMaterial = new CANNON.ContactMaterial(cubeWorldMaterial, floorMaterial, {
	friction: 0.1, `摩擦力`
	restitution: 0.7 `弹性`
})

`将,材料的关联设置,添加到物理世界`
world.addContactMaterial(defaultContactMaterial)

`设置,物理世界,碰撞的默认材质,,如果物理世界的物体没有设置这个,就用这个`
world.defaultContactMaterial = defaultContactMaterial

// -------------------------------------------------------------------------------

// 渲染器透明【渲染器要放在物理世界相关内容后面,不然效果不同】
const renderer = new THREE.WebGLRenderer({ alpha: true })
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
document.body.appendChild(renderer.domElement)

// 环境光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5)
scene.add(ambientLight)
// 平行光
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5)
directionalLight.castShadow = true
directionalLight.position.set(0, 8, 0) // 平行光的位置
scene.add(directionalLight)
// 平行光辅助器
const directionalLightHelp = new THREE.DirectionalLightHelper(directionalLight)
scene.add(directionalLightHelp)
// 创建轨道控制器
const controls = new OrbitControls(camera, renderer.domElement)
controls.enableDamping = true
// 世界坐标辅助器
const axesHelper = new THREE.AxesHelper(5)
scene.add(axesHelper)


const clock = new THREE.Clock()

const render = () => {
	// getDelta():返回,距离上次调用,getDelta(),以来经过的秒数
	let deltaTime = clock.getDelta()
	
	/*
	  world.step():更新物理引擎里的世界物体
	    参数一:指定了,物理引擎内部模拟的时间步长(以秒为单位),
	           在这里,设置为,大约每1/120秒更新一次物理世界,
	    参数而:实际的时间差,它允许物理引擎根据实际的帧率调整其模拟,
	           以保持物理行为的稳定性、一致性,
	*/
	world.step(1 / 120, deltaTime)
	
	// 将物理引擎的sphereBody的位置,复制给渲染引擎的sphere
	// cube.position.copy(sphereBody.position)
	cubeArr.forEach(item => {
		item.mesh.position.copy(item.body.position)
		// 设置渲染的物体跟随物理的物体旋转
		item.mesh.quaternion.copy(item.body.quaternion)
	})
	
	renderer.render(scene, camera)
	requestAnimationFrame(render)
}
render()


window.addEventListener('resize', () => {
	// 重置相机的宽高比
	camera.aspect = window.innerWidth / window.innerHeight
	// 更新相机的投影矩阵
	camera.updateProjectionMatrix()
	
	// 重置渲染器的宽高比
	renderer.setSize(window.innerWidth, window.innerHeight)
	// 更新渲染器的像素比
	renderer.setPixelRatio(window.devicePixelRatio)
})
相关推荐
一嘴一个橘子5 天前
3.js - 漫天孔明灯(使用OrbitControls 锁定相机镜头)
three.js
一嘴一个橘子6 天前
3.js - 着色器设置点材质(螺旋星系特效)
three.js
Ian10259 天前
Three.js new THREE.TextureLoader()纹理贴图使用png图片显示为黑色
前端·javascript·webgl·three.js·贴图·三维
Jedi Hongbin15 天前
THREE.JS像素风格渲染
javascript·three.js·shader·后处理
unix2linux21 天前
Parade Series - 3D Modeling
python·flask·html·jquery·webgl·three.js
zj靖1 个月前
three.js 几何体、材质和网格模型
three.js
一嘴一个橘子1 个月前
3.js - 顶点着色器、片元着色器的联系
three.js
Jedi Hongbin1 个月前
Threejs&WebGPU运动残影demo
javascript·three.js
Virtual091 个月前
借助Three.js,我们也能实现一个地球仪旋转
前端·javascript·three.js