likes
comments
collection
share

three.js + vue3 (三) 360全景看房(下篇)

作者站长头像
站长
· 阅读数 53

three.js + vue3 (三) 360全景看房(下篇)

好的,自然而然的也来到了下篇,那就是切换场景,如果看了上篇没下篇,那我真忍不了,所以我俩篇一起操作,这样大家都舒服了😌

环境搭建

three.js + vue3 (三) 360全景看房(下篇)

场景切换

这里主要用到的就是精灵sprite,我也封装了一个class,基本上俩个class就能实现360全景切换了,其实这么看来的话还是比较轻松的有没有!

一、canvas 创建样式

在mesh文件夹下创建一个sprite.js文件,这里我用了canvas直接去画了个样式和文字,也可以贴纹理(这个可以自己去研究)

three.js + vue3 (三) 360全景看房(下篇)

二、创建精灵图

创建精灵图之后,引入到room中new出来,这时候就有一个精灵样式了 three.js + vue3 (三) 360全景看房(下篇)

three.js + vue3 (三) 360全景看房(下篇)

three.js + vue3 (三) 360全景看房(下篇)

为什么是-4,0,3呢,其实你可以缩小去看看,给大家画了个坐标,希望能更好的理解,其实你自己画个图就理解了

three.js + vue3 (三) 360全景看房(下篇)

三、创建射线

那么问题来了,我该怎么才能知道,我点的是厨房呢 这里用到了射线碰撞的知识,大家可以去看看射线的文档,就是判断是否碰到了,碰到了就会返回再数组里,然后我再判断数组是否有㊗值,有的话说明点了厨房

three.js + vue3 (三) 360全景看房(下篇)

四、创建点击函数

如果我知道了它点击了厨房,但是我该怎么让外面知道是点击了厨房,然后外面接受到了这个信息,并作出场景切换的操作呢。

three.js + vue3 (三) 360全景看房(下篇)

three.js + vue3 (三) 360全景看房(下篇)

五、创建厨房,切换场景

创建厨房的位置,厨房的位置一定是厨房文字的那边,因为后面动画的时候移动过去的时候合理,这里一个盒子是10,那这个位置就是-10,0,10,大家可以去画一下。

three.js + vue3 (三) 360全景看房(下篇)

three.js + vue3 (三) 360全景看房(下篇)

好啦!切换厨房的场景就大功告成了

六、厨房回客厅

一样的步骤,因为都封装好了,直接调用就行,大家也可以根据上面的自己去完成,这里就贴个代码了,动画过渡的duration,要是觉着快的话就还0.5 这里自己调时间就行

three.js + vue3 (三) 360全景看房(下篇)

完整代码

import * as THREE from "three";
import scene from '@/three/common/scene'
import camera from '@/three/common/camera'

export default class SpriteText {
  // 1 - 名称
  // 2 - 位置
  constructor (text, position) {
    this.callbacks = [];
    const canvas = document.createElement('canvas')
    canvas.width = 1024;
    canvas.height = 1024;
    const context = canvas.getContext('2d');
    context.fillStyle = 'rgba(100, 100, 100, 0.7)';
    context.fillRect(0, 256, 1024, 512);
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.font = 'bold 200px Arial';
    context.fillStyle = 'white';
    context.fillText(text, 512, 512);
    // 放入canvas纹理加载器中
    let texture = new THREE.CanvasTexture(canvas);
    // 创建精灵材质
    const material = new THREE.SpriteMaterial({
      map: texture,
      transparent: true
    })
    // 创建精灵图
    const sprite = new THREE.Sprite(material);
    // 精灵图的位置
    sprite.position.copy(position);
    this.sprite = sprite;
    // 加入场景中
    scene.add(sprite);

    let mouse = new THREE.Vector2();
    let raycaster = new THREE.Raycaster();
    window.addEventListener('click', (event) => {
      mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
      mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
      raycaster.setFromCamera(mouse, camera)
      let intersects = raycaster.intersectObject(sprite);
      console.log('intersects', intersects);
      if (intersects.length > 0) {
        this.callbacks.forEach(item => {
          item();
        })
      }
    })
  }
  onClick(callback) {
    this.callbacks.push(callback);
  }
}




好啦!相信有这一个切换场景,其他房间都是一样的,我就不一一展示了,大家可以自己去把剩下的都补上,希望大家都能有自己满意的工作!

转载自:https://juejin.cn/post/7230745439125749821
评论
请登录