three.js使用光线投射对象Raycaster在屏幕中拾取/选取对象(vue中使用three.js60)

1.demo效果

在这里插入图片描述

如上图,该demo实现鼠标可以在屏幕中选取球体、圆柱或方块,点击时改变其透明度。若勾选showRay属性。鼠标滑过对象时出现模拟投射射线的红色线条

2.知识要点

2.1 光线投射对象Raycaster

该对象用于在三维空间中选取某个对象。其原理是从某一点发射一条射线。如果这条射线穿过一个对象。那么就会选中这个对象。

2.1.1 创建光线投射对象

创建光投射对象通过new THREE.Raycaster(origin, direction, near, far)语句创建。其参数说明如下:

  1. origin -光线投射的原点,Vector3类型。
  2. direction -射线的方向,Vector3类型。
  3. near -投射近点,不能为负值,应该小于far,其默认值为0
  4. far -投射远点,不能小于near,其默认值为无穷大

关于参数near和far做一下特别说明:如下图如果选取对象在射线选取范围内才可以被选中,
在这里插入图片描述

2.1.2获取射线交叉对象

创建的光线投射对象有一个intersectObject()方法用来获取射线交叉的对象,使用方法如下

const raycaster = new THREE.Raycaster(origin, direction, near, far)
const arr= raycaster.intersectObjects(object, recursive, optionalTarget)

raycaster.intersectObjects()参数

  1. object-要检查的是否与射线相交的对象,Object3D类型。
  2. recursive-是否检查所有后代,可选默认为false,Boolean类型。
  3. optionalTarget-可选参数,放置结果的目标数组。Array类型。若使用这个参数返回检查结果则在每次调用之前必须清空这个数组

raycaster.intersectObjects()的返回值
在这里插入图片描述

  1. distance -射线投射原点和相交部分之间的距离。
  2. point -相交部分的坐标。
  3. face -相交的面。
  4. faceIndex -相交的面的索引。
  5. object -相交的物体。
  6. uv -相交部分的点的UV坐标。

使用示例

//示例1-射线只检查指定的成员-球体、圆柱、方块
const intersects = raycaster.intersectObjects([
  this.sphere,
  this.cylinder,
  this.cube
])
//示例2-射线检查所有指定对象的后代
const intersects = raycaster.intersectObjects(this.scene.children, true)

// 设置选中对象透明度为0.1
if (intersects.length > 0) {
  intersects[0].object.material.transparent = true
  intersects[0].object.material.opacity = 0.1
}

3.实现要点

3.1 添加鼠标点击和悬浮监听事件

  mounted() {
    document.addEventListener('mousedown', this.onDocumentMouseDown, false)
    document.addEventListener('mousemove', this.onDocumentMouseMove, false)
  }

3.2 屏幕坐标系转换为three.js 坐标系

//屏幕坐标系转换为three.js坐标系
let vector = new THREE.Vector3(
  (event.clientX / window.innerWidth) * 2 - 1,
  -(event.clientY / window.innerHeight) * 2 + 1,
  0.5
)

3.3 创建光线投射对象获取选取对象

 // 创建光线投射对象
 const raycaster = new THREE.Raycaster(
   this.camera.position,
   vector.sub(this.camera.position).normalize()
 )

 //射线只检查指定的成员-球体、圆柱、方块
 const intersects = raycaster.intersectObjects([
   this.sphere,
   this.cylinder,
   this.cube
 ])

3.4 选中对象处理

// 设置选中对象透明度为0.1
if (intersects.length > 0) {
  intersects[0].object.material.transparent = true
  intersects[0].object.material.opacity = 0.1
}

// 创建模拟射线
if (intersects.length > 0) {
  const points = []
  // 创建模拟射线的起点和终点
  points.push(new THREE.Vector3(-30, 39.8, 30))
  points.push(intersects[0].point)

  const mat = new THREE.MeshBasicMaterial({
    color: 0xff0000,
    transparent: true,
    opacity: 0.6
  })

  //创建管道几何体模拟射线
  const tubeGeometry = new THREE.TubeGeometry(
    new THREE.CatmullRomCurve3(points),
    60,
    0.001
  )

  if (this.tube) this.scene.remove(this.tube)
  if (this.properties.showRay) {
    //创建模拟射线的对象并添加到场景
    this.tube = new THREE.Mesh(tubeGeometry, mat)
    this.scene.add(this.tube)
  }
}

4.demo代码

<template>
  <div>
    <div id="container"></div>
    <div class="controls-box">
      <section>
        <el-row>
          <div v-for="(item,key) in properties" :key="key">
            <div v-if="item&&item.name!=undefined">
              <el-col :span="8">
                <span class="vertice-span">{{item.name}}</span>
              </el-col>
              <el-col :span="13">
                <el-slider v-model="item.value" :min="item.min" :max="item.max" :step="item.step" :format-tooltip="formatTooltip" @change="redraw"></el-slider>
              </el-col>
              <el-col :span="3">
                <span class="vertice-span">{{item.value}}</span>
              </el-col>
            </div>
          </div>
        </el-row>
        <el-row>
          <el-checkbox v-model="properties.showRay">showRay</el-checkbox>
        </el-row>
      </section>
    </div>
  </div>
</template>

<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js'
export default {
  components: {},
  data() {
    return {
      properties: {
        rotationSpeed: {
          name: 'rotationSpeed',
          value: 0.02,
          min: 0,
          max: 0.5,
          step: 0.01
        },
        bouncingSpeed: {
          name: 'bouncingSpeed',
          value: 0.03,
          min: 0,
          max: 0.5,
          step: 0.01
        },
        scalingSpeed: {
          name: 'scalingSpeed',
          value: 0.03,
          min: 0,
          max: 0.5,
          step: 0.01
        },
        showRay: false
      },
      cube: null,
      sphere: null,
      cylinder: null,
      step: 0,
      scalingStep: 0,
      camera: null,
      scene: null,
      renderer: null,
      controls: null,
      hoverTarget: null,
      mouse: null
    }
  },
  mounted() {
    document.addEventListener('mousedown', this.onDocumentMouseDown, false)
    document.addEventListener('mousemove', this.onDocumentMouseMove, false)
    this.init()
  },
  methods: {
    formatTooltip(val) {
      return val
    },
    onDocumentMouseDown(event) {
      //屏幕坐标系转换为three.js坐标系
      let vector = new THREE.Vector3(
        (event.clientX / window.innerWidth) * 2 - 1,
        -(event.clientY / window.innerHeight) * 2 + 1,
        0.5
      )
      vector = vector.unproject(this.camera)

      // 创建光线投射对象
      const raycaster = new THREE.Raycaster(
        this.camera.position,
        vector.sub(this.camera.position).normalize()
      )

      //射线只检查指定的成员-球体、圆柱、方块
      const intersects = raycaster.intersectObjects([
        this.sphere,
        this.cylinder,
        this.cube
      ])

      //const intersects = raycaster.intersectObjects(this.scene.children, true)//射线检查所有指定对象的成员
      // 设置选中对象透明度为0.1
      if (intersects.length > 0) {
        intersects[0].object.material.transparent = true
        intersects[0].object.material.opacity = 0.1
      }
    },

    onDocumentMouseMove(event) {
      if (this.properties.showRay) {
        //屏幕坐标系转换为three.js坐标系
        let vector = new THREE.Vector3(
          (event.clientX / window.innerWidth) * 2 - 1,
          -(event.clientY / window.innerHeight) * 2 + 1,
          0.5
        )
        vector = vector.unproject(this.camera)

        // 创建光线投射,用于在三维空间中计算出鼠标移过了什么物体
        const raycaster = new THREE.Raycaster(
          this.camera.position,
          vector.sub(this.camera.position).normalize()
        )

        //射线只检查指定的成员-球体、圆柱、方块
        const intersects = raycaster.intersectObjects([
          this.sphere,
          this.cylinder,
          this.cube
        ])
        //console.log(intersects)
        if (intersects.length > 0) {
          const points = []
          // 创建模拟射线的起点和终点
          points.push(new THREE.Vector3(-30, 39.8, 30))
          points.push(intersects[0].point)

          const mat = new THREE.MeshBasicMaterial({
            color: 0xff0000,
            transparent: true,
            opacity: 0.6
          })

          //创建管道几何体模拟射线
          const tubeGeometry = new THREE.TubeGeometry(
            new THREE.CatmullRomCurve3(points),
            60,
            0.001
          )

          if (this.tube) this.scene.remove(this.tube)
          if (this.properties.showRay) {
            //创建模拟射线的对象并添加到场景
            this.tube = new THREE.Mesh(tubeGeometry, mat)
            this.scene.add(this.tube)
          }
        }
      }
    },

    // 初始化
    init() {
      this.createScene() // 创建场景
      this.createMeshs() // 创建网格对象
      this.createLight() // 创建光源
      this.createCamera() // 创建相机
      this.createRender() // 创建渲染器
      this.createControls() // 创建控件对象
      this.render() // 渲染
    },
    // 创建场景
    createScene() {
      this.scene = new THREE.Scene()
    },

    // 创建光源
    createLight() {
      // 添加聚光灯
      const spotLight = new THREE.SpotLight(0xffffff)
      spotLight.position.set(-40, 60, 20)
      spotLight.castShadow = true
      this.scene.add(spotLight) // 聚光灯添加到场景中
      // 环境光
      const ambientLight = new THREE.AmbientLight(0x0c0c0c)
      this.scene.add(ambientLight)
    },
    // 创建相机
    createCamera() {
      const element = document.getElementById('container')
      const width = element.clientWidth // 窗口宽度
      const height = element.clientHeight // 窗口高度
      const k = width / height // 窗口宽高比
      // PerspectiveCamera( fov, aspect, near, far )
      this.camera = new THREE.PerspectiveCamera(45, k, 0.1, 1000)

      this.camera.position.set(-30, 40, 30) // 设置相机位置
      this.camera.lookAt(new THREE.Vector3(5, 0, 0)) // 设置相机方向
      this.scene.add(this.camera)
    },
    // 创建渲染器
    createRender() {
      const element = document.getElementById('container')
      this.renderer = new THREE.WebGLRenderer()
      this.renderer.setSize(element.clientWidth, element.clientHeight) // 设置渲染区域尺寸
      this.renderer.setClearColor(0x3f3f3f, 1) // 设置背景颜色
      element.appendChild(this.renderer.domElement)
    },

    // 创建网格对象
    createMeshs() {
      // 创建底板并添加到场景
      const planeGeometry = new THREE.PlaneGeometry(60, 20, 1, 1)
      const planeMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff })
      const plane = new THREE.Mesh(planeGeometry, planeMaterial)
      plane.rotation.x = -0.5 * Math.PI
      plane.position.x = 15
      plane.position.y = 0
      plane.position.z = 0
      this.scene.add(plane)

      // 创建方块并添加到场景
      const cubeGeometry = new THREE.BoxGeometry(4, 4, 4)
      const cubeMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 })
      this.cube = new THREE.Mesh(cubeGeometry, cubeMaterial)
      this.cube.position.set(-9, 3, 0)
      this.scene.add(this.cube)

      // 创建球体并添加到场景
      const sphereGeometry = new THREE.SphereGeometry(4, 20, 20)
      const sphereMaterial = new THREE.MeshLambertMaterial({ color: 0x7777ff })
      this.sphere = new THREE.Mesh(sphereGeometry, sphereMaterial)
      this.sphere.position.set(20, 0, 2)
      this.scene.add(this.sphere)

      // 创建圆柱并添加到场景
      const cylinderGeometry = new THREE.CylinderGeometry(2, 2, 20)
      const cylinderMaterial = new THREE.MeshLambertMaterial({
        color: 0x77ff77
      })
      this.cylinder = new THREE.Mesh(cylinderGeometry, cylinderMaterial)
      this.cylinder.position.set(0, 0, 1)
      this.scene.add(this.cylinder)
    },

    redraw() {
      this.scene.remove(this.cube)
      this.scene.remove(this.sphere)
      this.scene.remove(this.cylinder)
      this.createMeshs()
    },
    animation() {
      // 方块旋转
      this.cube.rotation.x += this.properties.rotationSpeed.value
      this.cube.rotation.y += this.properties.rotationSpeed.value
      this.cube.rotation.z += this.properties.rotationSpeed.value

      // 球体上下弧形跳动
      this.step += this.properties.bouncingSpeed.value
      this.sphere.position.x = 20 + 10 * Math.cos(this.step)
      this.sphere.position.y = 2 + 10 * Math.abs(Math.sin(this.step))

      // 圆柱放大缩小
      this.scalingStep += this.properties.scalingSpeed.value
      const scaleX = Math.abs(Math.sin(this.scalingStep / 4))
      const scaleY = Math.abs(Math.cos(this.scalingStep / 5))
      const scaleZ = Math.abs(Math.sin(this.scalingStep / 7))
      this.cylinder.scale.set(scaleX, scaleY, scaleZ)
    },
    render() {
      this.animation()
      this.renderer.render(this.scene, this.camera)
      requestAnimationFrame(this.render)
    },
    // 创建控件对象
    createControls() {
      this.controls = new OrbitControls(this.camera, this.renderer.domElement)
    }
  }
}
</script>

<style>
#container {
  position: absolute;
  width: 100%;
  height: 100%;
}
.controls-box {
  position: absolute;
  right: 5px;
  top: 5px;
  width: 300px;
  padding: 10px;
  background-color: #fff;
  border: 1px solid #c3c3c3;
}
.vertice-span {
  line-height: 38px;
  padding: 0 2px 0 10px;
}
</style>

  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值