1. 程式人生 > 其它 >Three特效-道路流光特效

Three特效-道路流光特效

技術標籤:Threewebglthree.js

Three特效-道路流光特效

概述

使用Three.js來建立智慧城市場景中的道路流光動畫,主要原理是使用貼圖動畫,效果圖:
在這裡插入圖片描述
貼圖素材:
在這裡插入圖片描述

程式碼

  1. 建立道路頂點陣列
// 建立頂點陣列
  let points = [new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(10, 0, 0),
    new THREE.Vector3(10, 0, 10),
    new THREE.Vector3(0, 0, 10)
  ]
  1. 使用CatmullRomCurve3生成曲線
    CatmullRomCurve3(點:陣列,閉合:布林值,curveType:字串,張力:浮點)
    points – Vector3點陣列
    closed –該曲線是否閉合,替換為假
    curveType –曲線的型別,交替變數向心。
    張力–曲線的張力,交替為0.5。
let curve = new THREE.CatmullRomCurve3(points) // 曲線路徑
  1. 使用TubeGeometry建立管道
    TubeGeometry(路徑:曲線,管狀段:整數,半徑:浮點,徑向段:整數,封閉:布林)
    tubularSegments —整數-組成該管道的分段數,相互之間的距離為64。radius —浮點-管道的 截面,其大小為1。radialSegments—整數-- 路徑-曲線-一個由基類曲線繼承而來的路徑。close —布林型管道的交替是否閉合,替換為false。
// 建立管道
let tubeGeometry = new THREE.TubeGeometry(curve, 80, 0.1)
  1. 建立材質並在動畫函式中使用貼圖位移
  let texture = new THREE.TextureLoader().load("line.png")
  texture.wrapS = texture.wrapT = THREE.RepeatWrapping; 
  texture.repeat.set(1, 1)
  texture.needsUpdate = true

  let material = new THREE.MeshBasicMaterial
({ map: texture, side: THREE.BackSide, transparent: true })
  1. 建立mesh
let mesh = new THREE.Mesh(tubeGeometry, material);

scene.add(mesh)

完整程式碼

let texture = new THREE.TextureLoader().load("line.png")
  texture.wrapS = texture.wrapT = THREE.RepeatWrapping; //每個都重複
  texture.repeat.set(1, 1)
  texture.needsUpdate = true

  let material = new THREE.MeshBasicMaterial({
    map: texture,
    side: THREE.BackSide,
    transparent: true
  })

  // 建立頂點陣列
  let points = [new THREE.Vector3(0, 0, 0),
    new THREE.Vector3(10, 0, 0),
    new THREE.Vector3(10, 0, 10),
    new THREE.Vector3(0, 0, 10)
  ]

  // CatmullRomCurve3建立一條平滑的三維樣條曲線
  let curve = new THREE.CatmullRomCurve3(points) // 曲線路徑

  // 建立管道
  let tubeGeometry = new THREE.TubeGeometry(curve, 80, 0.1)
  
  let mesh = new THREE.Mesh(tubeGeometry, material);

  scene.add(mesh)

  function animate() {
	// 一定要在此函式中呼叫
    if(texture) texture.offset.x -= 0.01
    requestAnimationFrame(animate)
  }

  animate()