[Babylonjs]创建vite + vue3 + Babylonjs项目

118 阅读1分钟

参考官方文档:Vue | Babylon.js Documentation

1. 创建 vite + vue3 项目

npm create vite@latest my-vue-babylon -- --template vue-ts

2. 安装babylon.js

npm install @babylonjs/core @babylonjs/gui @babylonjs/loaders

不使用esm

npm install babylonjs babylonjs-gui babylonjs-loaders

3. 添加组件

  1. 添加文件 components/Demo.vue

    <template>
      <canvas ref="canvas" class="canvas"></canvas>
    </template>
    <script lang="ts" setup>
    import {
      ArcRotateCamera,
      Color3,
      Color4,
      Engine,
      HemisphericLight,
      MeshBuilder,
      Scene,
      StandardMaterial,
      Vector3
    } from '@babylonjs/core'
    import { onMounted, ref } from 'vue'
    
    const canvas = ref<HTMLCanvasElement>()
    
    const createScene = () => {
      if (!canvas.value) return
      const engine = new Engine(canvas.value, true, { stencil: true })
      const scene = new Scene(engine)
      scene.clearColor = new Color4(0, 0, 0, 0)
    
      const camera = new ArcRotateCamera(
        'camera',
        -Math.PI / 2,
        Math.PI / 2.5,
        15,
        new Vector3(0, 0, 0)
      )
      camera.attachControl(canvas.value, true)
    
      const light = new HemisphericLight('light', new Vector3(0, 1, 0), scene)
      light.intensity = 0.7
    
      const box = MeshBuilder.CreateBox('box', { size: 2 }, scene)
      box.position.y = 1
      const boxMat = new StandardMaterial('boxMat', scene)
      boxMat.diffuseColor = new Color3(0.5, 0.5, 1)
      box.material = boxMat
    
      engine.runRenderLoop(() => {
        scene.render()
      })
    
      window.addEventListener('resize', () => {
        engine.resize()
      })
    }
    
    onMounted(() => {
      createScene()
    })
    </script>
    
  2. 修改App.vue

    <script setup lang="ts">
    import Demo from './components/Demo.vue'
    </script>
    
    <template>
      <Demo />
    </template>
    
  3. 修改style.css

    body, html, canvas, #app {
      width: 100%;
      height: 100%;
      margin: 0;
      padding: 0;
      overflow: hidden;
    }
    

3. 启动

npm run dev

image.png

4. 高亮网格

const highlight = new HighlightLayer('highlight', scene)
highlight.addMesh(box, new Color3(1, 0, 0))
highlight.blurHorizontalSize = 0.5
highlight.blurVerticalSize = 0.5

image.png

5. 添加鼠标事件

scene.onPointerObservable.add((pointerInfo) => {
  switch (pointerInfo.type) {
    case PointerEventTypes.POINTERDOWN:
      if (pointerInfo.pickInfo?.hit && pointerInfo.pickInfo.pickedMesh === box) {
        highlight.addMesh(box, new Color3(1, 0, 0))
      } else {
        highlight.removeMesh(box)
      }
      break
    default:
      break
  }
})

6. 启用网格的鼠标移动事件

要启用鼠标移动到网格上的事件监听,需要设置属性enablePointerMoveEvents 值为 true