three.js使用光线投射对象Raycaster在屏幕中拾取/选取对象(vue中使用three.js60)
用鼠标在屏幕中拾取/选取对象
- 1.demo效果
- 2.知识要点
- 2.1 光线投射对象Raycaster
- 2.1.1 创建光线投射对象
- 2.1.2获取射线交叉对象
- 3.实现要点
- 3.1 添加鼠标点击和悬浮监听事件
- 3.2 屏幕坐标系转换为three.js 坐标系
- 3.3 创建光线投射对象获取选取对象
- 3.4 选中对象处理
- 4.demo代码
1.demo效果
如上图,该demo实现鼠标可以在屏幕中选取球体、圆柱或方块,点击时改变其透明度。若勾选showRay属性。鼠标滑过对象时出现模拟投射射线的红色线条
2.知识要点
2.1 光线投射对象Raycaster
该对象用于在三维空间中选取某个对象。其原理是从某一点发射一条射线。如果这条射线穿过一个对象。那么就会选中这个对象。
2.1.1 创建光线投射对象
创建光投射对象通过new THREE.Raycaster(origin, direction, near, far)
语句创建。其参数说明如下:
- origin -光线投射的原点,Vector3类型。
- direction -射线的方向,Vector3类型。
- near -投射近点,不能为负值,应该小于far,其默认值为0
- 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()参数
- object-要检查的是否与射线相交的对象,Object3D类型。
- recursive-是否检查所有后代,可选默认为false,Boolean类型。
- optionalTarget-可选参数,放置结果的目标数组。Array类型。
若使用这个参数返回检查结果则在每次调用之前必须清空这个数组
raycaster.intersectObjects()的返回值
- distance -射线投射原点和相交部分之间的距离。
- point -相交部分的坐标。
- face -相交的面。
- faceIndex -相交的面的索引。
- object -相交的物体。
- 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 = trueintersects[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 = trueintersects[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.1if (intersects.length > 0) {intersects[0].object.material.transparent = trueintersects[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 = truethis.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.PIplane.position.x = 15plane.position.y = 0plane.position.z = 0this.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.valuethis.cube.rotation.y += this.properties.rotationSpeed.valuethis.cube.rotation.z += this.properties.rotationSpeed.value// 球体上下弧形跳动this.step += this.properties.bouncingSpeed.valuethis.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.valueconst 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>
three.js使用光线投射对象Raycaster在屏幕中拾取/选取对象(vue中使用three.js60)相关推荐
- 微信js扫一扫,扫条形码去掉code_128。在vue中封装全局对象的方法,封装微信js-sdk权限验证的方法
微信公众号在调用扫一扫功能时,一维码(条形码)在直接返回结果时会在结果前带上EAN_8, EAN_13, CODE_25, CODE_39, CODE_128, UPC_A, UPC_E wx.sca ...
- 创建第一个three.js三维场景,可通过鼠标缩放与移动方块(vue中使用three.js02)
three.js创建可鼠标操作立方体 一.three.js创建鼠标操作立方体几个重要步骤 1.创建场景 2.创建网格模型 3.创建光源 4.创建相机 5.创建渲染器 6.创建控件对象 7.渲染 二.全 ...
- vue.js从入门到深入再到随心而用————vue的沿途风景
vue的沿途风景 1.vue基础知识 1.1初步认识vue.js 1.2v-clock系列指令 1.3利用v-clock完成跑马灯效果 1.4v-model的学习 1.5事件修饰符的学习 1.6利用v ...
- TSINGSEE青犀视频使用Vue.js搭建前端启动后共享屏幕无法获取音视频流问题解决
TSINGSEE青犀视频云边端架构产品的前端搭建大多是通过Vue来完成的,Vue的核心库只关注视图层,非常容易与其它库或已有项目整合,并且有能力驱动采用单文件组件和Vue生态系统支持的库开发的复杂单页 ...
- three.js创建光线_使用Three.js在图像上创建波动效果
three.js创建光线 View demo 查看演示Download Source 下载源 Waves! Because who does not enjoy the visual comfort ...
- js浮动广告框(可根据屏幕大小自动调整位置)
js浮动广告框(可根据屏幕大小自动调整位置) 左下角 右下角 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN ...
- 高德地图中加载three.js(vue中)(封装
这几天公司有一个要结合高德地图的智慧园区的项目(大致就是在3d地图中加载自己的three.js模型) 1.首先要引入高德地图 官方文档给出来的引用方法 <template><div ...
- vue 计算屏幕的高度_学习Vue可以参考的10个开源项目——OpenSource
介绍 今天文章重点介绍一些最佳的Vue.js开源项目.Vue.js是一个JavaScript框架,主要专注于在应用程序项目中开发用户界面.Vue是一个简单的最小核心,具有可逐步采用的堆栈,可以处理任何 ...
- 前端:JS/28/CSS DOM动态样式(style对象,style 对象属性与CSS属性的转换),Event DOM,事件对象简介(DOM和IE中的Event对象),实例:点出满天小星星
CSS DOM动态样式 使用JS操作CSS中的各个属性: JS只能操作或修改行内样式,如:imgObjstyle.border = "1px solid red"; 对于类样式,通 ...
最新文章
- vCenter 部件关系简介 网络原理
- java opencv 平移_如何使用opencv pnpRansac()函数中的平移矩阵和旋转矩阵设置Rajawali相机的旋转?...
- 【转】The test form is only available for requests from the local machine 解决方法
- 互联网时代的应用设计,互联网营销
- java scala 获取类_在Scala 2.10中获取java.lang.Class [T]的Scala类型
- Github PageHelper 原理解析
- 百度吉利成立的汽车公司名称曝光,百度持股55%
- SharePoint 站点出现Http 503 错误
- MFC体系结构(3)
- Hibernate(十二):HQL查询(一)
- Android Toast 设置到屏幕中间,自定义Toast的实现方法,及其说明
- pythondocx更新目录_python根目录
- Linux基础-15-samba服务
- getch方法_如何实现getch()函数的功能
- js日期格式化 YYMMDD 转 YY-MM-DD 转 YY年MM月DD日
- 动态添加、删除文本框
- zip文件命令 linux,在Linux上压缩文件:zip命令的各种变体及用法
- Android 文字转语音2种方式
- 安卓系统开机时间优化分析
- 解决 Python 报错SyntaxError: Missing parentheses in call to 'print'
热门文章
- 西门子1200PLC的MODBUS_RTU轮询程序
- spring boot 2.0 redis 分布式锁
- 全球与中国LED检查灯市场深度研究分析报告
- cas:337526-88-2 ;Ir(bt)2 (acac),齐岳提供金属配合物材料
- 「UG/NX」BlockUI 控件集合
- 《计算机网络与因特网》复习纲要
- 解题报告 (十三) 尺取法
- 看这篇就够了!能源企业数字化升级,推动绿色低碳发展
- 【Unity小游戏】打字消除字母
- 中文OCR光学字符检测与识别二:用最先进的DBNet训练自己的数据集检测中文文本