目录

项目搭建

初始化three.js基础代码

设置环境纹理加载模型

使用Cannon-es实现物理世界


今天简单实现一个three.js的小Demo,加强自己对three知识的掌握与学习,只有在项目中才能灵活将所学知识运用起来,话不多说直接开始。

项目搭建

本案例还是借助框架书写three项目,借用vite构建工具搭建vue项目,vite这个构建工具如果有不了解的朋友,可以参考我之前对其讲解的文章:vite脚手架的搭建与使用 。搭建完成之后,用编辑器打开该项目,在终端执行 npm i 安装一下依赖,安装完成之后终端在安装 npm i three 即可。

<template>
  <!-- 踢球游戏 -->
  <kickballGame></kickballGame>
</template>

<script setup>
import kickballGame from './components/kickballGame.vue';
</script>

<style lang="less">
  *{
    margin: 0;
    padding: 0;
  }
</style>

初始化three.js基础代码

three.js开启必须用到的基础代码如下:

导入three库

import * as THREE from 'three'

初始化场景

const scene = new THREE.Scene()

初始化相机

// 初始化相机
const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
camera.position.set(4,2,0)
camera.updateProjectionMatrix()

初始化渲染器

// 初始化渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true, // 设置抗锯齿
  logarithmicDepthBuffer: true, // 使用对数缓存
})
renderer.setSize(window.innerWidth,window.innerHeight)
// 设置色调映射
renderer.toneMapping = THREE.ACESFilmicToneMapping
renderer.toneMappingExposure = 1
// 设置阴影
renderer.shadowMap.enabled = true
// 设置阴影类型,实现更加平滑和真实的阴影效果
renderer.shadowMap.type = THREE.PCFSoftShadowMap
document.body.appendChild(renderer.domElement)

监听屏幕大小的改变并导入控制器

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

// 初始化控制器
const controls = new OrbitControls(camera,renderer.domElement)
controls.enableDamping = true

// 监听屏幕大小变化
window.addEventListener("resize",()=>{ 
  renderer.setSize(window.innerWidth,window.innerHeight)
  camera.aspect = window.innerWidth/window.innerHeight
  camera.updateProjectionMatrix()
})

设置渲染函数

const render = () =>{ 
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}

ok,写完基础代码之后,接下来开始具体的Demo实操。

设置环境纹理加载模型

使用TextureLoader用于加载图片纹理的工具,将图片文件加载为 Three.js 中的纹理对象,并且可以将纹理应用到场景中的任何物体上,从而实现更加生动的渲染效果。

const texture = new THREE.TextureLoader()
texture.load("./textures/outdoor.jpg", (texture)=>{
  texture.mapping = THREE.EquirectangularReflectionMapping
  // 设置环境纹理
  scene.background = texture
  scene.environment = texture
  scene.backgroundBlurriness = 0.3 // 设置模糊度
})

Three.js--》实现3d踢球模型展示-LMLPHP

环境纹理设置完成之后通过GLTFLoader将GLTF格式的3D模型加载到网页上,以及使用DRACOLoader能够有效的压缩3D模型文件的大小,提高加载速度和用户体验。

import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";

// 解压模型
const dracoLoader = new DRACOLoader()
dracoLoader.setDecoderPath('./draco/')
// 加载模型
const gltfLoader = new GLTFLoader()
gltfLoader.setDRACOLoader(dracoLoader)
gltfLoader.load('./model/playground02.glb',(glb) => {
  const model = glb.scene
  scene.add(model)
})

设置聚光灯让球的阴影变得更明显:

// 添加聚光灯
const spotLight = new THREE.SpotLight(0xffffff)
spotLight.position.set(10,50,0)
spotLight.castShadow = true
spotLight.shadow.mapSize.width = 2048
spotLight.shadow.mapSize.height = 2048
spotLight.shadow.camera.near = 0.5
spotLight.shadow.camera.far = 500
spotLight.shadow.camera.fov = 30
spotLight.shadow.bias = -0.00008
spotLight.intensity = 0.1
scene.add(spotLight)

Three.js--》实现3d踢球模型展示-LMLPHP

使用Cannon-es实现物理世界

Cannon-es通常被用作物理引擎库,用于模拟三维场景中的物理效果。它可以实现碰撞检测、物体受力作用、模拟重力等功能,从而让3D场景更加真实和有趣。

这里终端先进行下载该相关库,然后进行实例化创建物理世界:

import * as CANNON from 'cannon-es'

// 初始化物理世界
const world = new CANNON.World()
world.gravity.set(0,-9.82,0)

let clock = new THREE.Clock()
// 设置渲染函数
const render = () =>{ 
  let delta = clock.getDelta()
  world.step(delta) // 更新物理世界
  if(ball && ballBody) {
    ball.position.copy(ballBody.position)
    ball.quaternion.copy(ballBody.quaternion)
  }
  controls.update()
  requestAnimationFrame(render)
  renderer.render(scene,camera)
}
render()

这里通过traverse遍历3D场景图,遍历场景中所有的对象(Object3D)以及它们的子对象,并对它们进行操作或者判断。

model.traverse((child)=>{
  if(child.isMesh && child.name.search(/Solid/ == -1)) {
    child.castShadow = true
    child.receiveShadow = true
    // 创建trimesh类型
    const trimesh = new CANNON.Trimesh(
      child.geometry.attributes.position.array,
      child.geometry.index.array
    )
    // 创建刚体
    const trimeshBody = new CANNON.Body({
      mass: 0,
      shape: trimesh
    })
    // 获取世界位置和旋转给到物理世界
    trimeshBody.position.copy(child.getWorldPosition(new THREE.Vector3()))
    trimeshBody.quaternion.copy(
      child.getWorldQuaternion(new THREE.Quaternion())
    )
    // 添加刚体到物理世界
    world.addBody(trimeshBody)

    if(child.name === "door"){
      child.material = new THREE.MeshBasicMaterial({
        color: 0x000000,
        opacity:0,
        transparent:true
      })
    }
  }
  if(child.name === 'Soccer_Ball'){
    ball = child
    // 创建球体
    const ballShape = new CANNON.Sphere(0.15)
    // 创建刚体
    ballBody = new CANNON.Body({
      mass: 1,
      position: new CANNON.Vec3(0,5,0),
      shape: ballShape
    })
    // 添加刚体到物理世界
    world.addBody(ballBody)
  }
  setTimeout(()=>{
    ballBody.position.set(0,15,0)
    ballBody.velocity.set(0,0,0)
    ballBody.angularVelocity.set(0,0,0)
  },2000)
})

通过设置点击事件动态让 Vec3(表示三维空间中的位置、方向、速度等值) ,为了显示改变数值大小,接下来定义一个变量来去动态改变其值,这里借用gsap动画库去让其一直重复的在某个范围来回的跳动:

let percentage = ref(30)

gsap.to(percentage, {
  duration: 1,
  value: 100,
  ease: "linear",
  repeat: -1,
  onUpdate: () =>{
    percentage.value = Math.floor(percentage.value)
  }
})

将动态变量设置在 Vec3 参数里面,如下:

let isClick = false
// 设置点击事件
window.addEventListener('click',()=>{
  if(isClick) return
  isClick = true
  ballBody.applyForce(
    new CANNON.Vec3(
      -1*percentage.value,
      6*percentage.value,
      (Math.random() - 0.5)*percentage.value
    ),ballBody.position)
  setTimeout(()=>{
    isClick = false
    ballBody.position.set(0,15,0)
    ballBody.velocity.set(0,0,0)
    ballBody.angularVelocity.set(0,0,0)
  },4000)
})

接下来通过html和css样式来动态显示数值的变化:

<template>
  <div class="">
    <h1>{{ percentage }}</h1>
  </div>
</template>

<style lang="less">
canvas {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
}
h1{
  position: fixed;
  left: 0;
  top: 0;
  z-index: 10;
  color: #fff;
}
</style>

Three.js--》实现3d踢球模型展示-LMLPHP

demo做完,给出本案例的完整代码:(获取素材也可以私信博主) 

<template>
  <div class="">
    <h1>{{ percentage }}</h1>
  </div>
</template>

<script setup>
import * as THREE from 'three'
import * as CANNON from 'cannon-es'
import { ref } from 'vue'
import gsap from 'gsap'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";

let percentage = ref(30)

gsap.to(percentage, {
  duration: 1,
  value: 100,
  ease: "linear",
  repeat: -1,
  onUpdate: () =>{
    percentage.value = Math.floor(percentage.value)
  }
})

// 初始化场景
const scene = new THREE.Scene()
// 初始化相机
const camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000)
camera.position.set(4,2,0)
camera.updateProjectionMatrix()

// 初始化渲染器
const renderer = new THREE.WebGLRenderer({
  antialias: true, // 设置抗锯齿
  logarithmicDepthBuffer: true, // 使用对数缓存
})
renderer.setSize(window.innerWidth,window.innerHeight)
// 设置色调映射
renderer.toneMapping = THREE.ACESFilmicToneMapping
renderer.toneMappingExposure = 1
// 设置阴影
renderer.shadowMap.enabled = true
// 设置阴影类型,实现更加平滑和真实的阴影效果
renderer.shadowMap.type = THREE.PCFSoftShadowMap
document.body.appendChild(renderer.domElement)

// 初始化控制器
const controls = new OrbitControls(camera,renderer.domElement)
controls.enableDamping = true

// 监听屏幕大小变化
window.addEventListener("resize",()=>{ 
  renderer.setSize(window.innerWidth,window.innerHeight)
  camera.aspect = window.innerWidth/window.innerHeight
  camera.updateProjectionMatrix()
})

// 设置环境纹理
const texture = new THREE.TextureLoader()
texture.load("./textures/outdoor.jpg", (texture)=>{
  texture.mapping = THREE.EquirectangularReflectionMapping
  // 设置环境纹理
  scene.background = texture
  scene.environment = texture
  scene.backgroundBlurriness = 0.3 // 设置模糊度
})

let ball,ballBody

// 解压模型
const dracoLoader = new DRACOLoader()
dracoLoader.setDecoderPath('./draco/')
// 加载模型
const gltfLoader = new GLTFLoader()
gltfLoader.setDRACOLoader(dracoLoader)
gltfLoader.load('./model/playground02.glb',(glb) => {
  const model = glb.scene
  model.traverse((child)=>{
    if(child.isMesh && child.name.search(/Solid/ == -1)) {
      child.castShadow = true
      child.receiveShadow = true
      // 创建trimesh类型
      const trimesh = new CANNON.Trimesh(
        child.geometry.attributes.position.array,
        child.geometry.index.array
      )
      // 创建刚体
      const trimeshBody = new CANNON.Body({
        mass: 0,
        shape: trimesh
      })
      // 获取世界位置和旋转给到物理世界
      trimeshBody.position.copy(child.getWorldPosition(new THREE.Vector3()))
      trimeshBody.quaternion.copy(
        child.getWorldQuaternion(new THREE.Quaternion())
      )
      // 添加刚体到物理世界
      world.addBody(trimeshBody)

      if(child.name === "door"){
        child.material = new THREE.MeshBasicMaterial({
          color: 0x000000,
          opacity:0,
          transparent:true
        })
      }
    }
    if(child.name === 'Soccer_Ball'){
      ball = child
      // 创建球体
      const ballShape = new CANNON.Sphere(0.15)
      // 创建刚体
      ballBody = new CANNON.Body({
        mass: 1,
        position: new CANNON.Vec3(0,5,0),
        shape: ballShape
      })
      // 添加刚体到物理世界
      world.addBody(ballBody)
    }
    setTimeout(()=>{
      ballBody.position.set(0,15,0)
      ballBody.velocity.set(0,0,0)
      ballBody.angularVelocity.set(0,0,0)
    },2000)
  })
  scene.add(model)
})

// 添加聚光灯
const spotLight = new THREE.SpotLight(0xffffff)
spotLight.position.set(10,50,0)
spotLight.castShadow = true
spotLight.shadow.mapSize.width = 2048
spotLight.shadow.mapSize.height = 2048
spotLight.shadow.camera.near = 0.5
spotLight.shadow.camera.far = 500
spotLight.shadow.camera.fov = 30
spotLight.shadow.bias = -0.00008
spotLight.intensity = 0.1
scene.add(spotLight)

// 初始化物理世界
const world = new CANNON.World()
world.gravity.set(0,-9.82,0)

let clock = new THREE.Clock()
// 设置渲染函数
const render = () =>{ 
  let delta = clock.getDelta()
  world.step(delta) // 更新物理世界
  if(ball && ballBody) {
    ball.position.copy(ballBody.position)
    ball.quaternion.copy(ballBody.quaternion)
  }
  controls.update()
  requestAnimationFrame(render)
  renderer.render(scene,camera)
}
render()

let isClick = false
// 设置点击事件
window.addEventListener('click',()=>{
  if(isClick) return
  isClick = true
  ballBody.applyForce(
    new CANNON.Vec3(
      -1*percentage.value,
      6*percentage.value,
      (Math.random() - 0.5)*percentage.value
    ),ballBody.position)
  setTimeout(()=>{
    isClick = false
    ballBody.position.set(0,15,0)
    ballBody.velocity.set(0,0,0)
    ballBody.angularVelocity.set(0,0,0)
  },4000)
})
</script>

<style lang="less">
canvas {
  position: fixed;
  left: 0;
  top: 0;
  width: 100vw;
  height: 100vh;
}
h1{
  position: fixed;
  left: 0;
  top: 0;
  z-index: 10;
  color: #fff;
}
</style>
06-03 07:25