three.js - Haunted House

2024-01-27  本文已影响0人  闪电西兰花
  // 导入three.js
  import * as THREE from 'three'
  // 导入轨道控制器
  import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
  // 导入gui
  import * as dat from 'dat.gui'

  /**
   * Scene
  **/
  const scene = new THREE.Scene()

  /**
   * Camera
  **/
  const camera = new THREE.PerspectiveCamera(
    75, // 视角
    window.innerWidth / window.innerHeight, // 视椎体长宽比
    0.1, // 近端面
    100 // 远端面
  )
  camera.position.set(4, 2, 5)

  /**
   * Renderer
  **/
  const renderer = new THREE.WebGLRenderer()
  renderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(renderer.domElement)

  /**
    * 坐标轴
  **/
  const axesHelper = new THREE.AxesHelper(5) // 坐标轴线段长度
  scene.add(axesHelper)

  /**
    控制器(使相机围绕目标运动)
  **/
  const controls = new OrbitControls(camera, renderer.domElement)
  controls.enableDamping = true // 添加轨道阻尼效果

  /**
    * 渲染
  **/
  const clock = new THREE.Clock()
  function animate () {
    let elapsedTime = clock.getElapsedTime()

    controls.update()
    requestAnimationFrame(animate)
    renderer.render(scene, camera)
  }
  animate()
  /**
    * Lights
  **/
  // AmbientLight
  const ambientLight = new THREE.AmbientLight('#fff', 0.8)
  scene.add(ambientLight)
  /**
    * gui
  **/
  const gui = new dat.GUI()
  gui.add(ambientLight, 'intensity').name('AmbientLight').min(0).max(1).step(0.001)
  /**
    * Fog
  **/
  const fog = new THREE.Fog('#262837', 1, 15) // color 距离camera的near 距离camera的far
  scene.fog = fog
renderer.setClearColor('#262837')
添加FOG和重置背景色之后的效果.png 添加textures之后的效果.png
  /*
    * Ghosts
  */
  const ghost1 = new THREE.PointLight('#ff00ff', 2, 3)
  scene.add(ghost1)

  const ghost2 = new THREE.PointLight('#00ffff', 2, 3)
  scene.add(ghost2)

  const ghost3 = new THREE.PointLight('#ffff00', 2, 3)
  scene.add(ghost3)
  /*
    * 渲染
  */
  const clock = new THREE.Clock()
  function animate () {
    let elapsedTime = clock.getElapsedTime()

    // Ghosts
    const ghost1Angle = elapsedTime * 0.5
    ghost1.position.x = Math.cos(ghost1Angle) * 4
    ghost1.position.z = Math.sin(ghost1Angle) * 4
    ghost1.position.y = Math.sin(elapsedTime * 3) // 上下起伏
    
    const ghost2Angle = - elapsedTime * 0.32 // 设为负数,与ghost1反向动画
    ghost2.position.x = Math.cos(ghost2Angle) * 5
    ghost2.position.z = Math.sin(ghost2Angle) * 5
    ghost2.position.y = Math.sin(elapsedTime * 4) + Math.sin(elapsedTime * 2.5)

    const ghost3Angle = - elapsedTime * 0.18
    ghost3.position.x = Math.cos(ghost3Angle) * (7 + Math.sin(elapsedTime * 0.32)) // 不固定旋转半径
    ghost3.position.z = Math.sin(ghost3Angle) * (7 + Math.sin(elapsedTime * 0.5)) // 不固定旋转半径
    ghost3.position.y = Math.sin(elapsedTime * 4) + Math.sin(elapsedTime * 2.5)


    controls.update()
    requestAnimationFrame(animate)
    renderer.render(scene, camera)
  }
  animate()
添加ghosts之后会随机出现的PointLight.png 最终静态效果.png
上一篇下一篇

猜你喜欢

热点阅读