提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
animation关于three.js 中如何实现动画效果,由于官方文档都有,这里记忆一些,特别的知识点和实现方式,一些方法等
一、实现代码
import * as THREE from 'three'
import gsap from 'gsap'
const scene = new THREE.Scene()
const geometry = new THREE.BoxGeometry(1,1,1)
const material = new THREE.MeshBasicMaterial({color:'#ff0000'})
const mesh = new THREE.Mesh(geometry,material)
scene.add(mesh)
const sizes = {
width:'800',
height:'600'
}
const camera = new THREE.PerspectiveCamera(75,sizes.width/sizes.height)
camera.position.z = 3
scene.add(camera)
const canvas = document.querySelector('.webgl')
const renderer = new THREE.WebGLRenderer({
canvas:canvas
})
renderer.setSize(sizes.width,sizes.height)
// Clock 跟踪时间
// const clock = new THREE.Clock()
// gasp
gsap.to(mesh.position,{duration:1,delay:1,x:2})
gsap.to(mesh.position,{duration:1,delay:2,x:2})
// animation
const tick = () =>{
// Clock
// const elapsedTime = clock.getElapsedTime()
// console.log(elapsedTime)
// Update objects
// mesh.position.x += 0.01
// mesh.rotation.y = elapsedTime
// 一秒一圈
// mesh.rotation.y = elapsedTime * Math.PI * 2
// Math.sin()
// mesh.position.y = Math.sin(elapsedTime)
// mesh.position.x = Math.cos(elapsedTime)
// camera.position.y = Math.sin(elapsedTime)
// camera.position.x = Math.cos(elapsedTime)
// 相机看立方体
// camera.lookAt(mesh.position)
// Render
renderer.render(scene,camera)
window.requestAnimationFrame(tick)
}
tick()
二、知识点
1.gsap
gsap 要进行下载依赖,通常情况下执行代码中的tick,通过window.requestAnimationFrame(tick)
就可以实现动画效果,但是也可以通过gsap实现红色立方体动起来
// duration 持续时间 delay 延迟 x方向 2个单位
gsap.to(mesh.position,{duration:1,delay:2,x:2})
npm i --save gsap@3.5.
2.camera.lookAt
camera.lookAt这个方法
camera.lookAt() 直接使用 应该是看向网格中心
相机结合camera.position 移动 以下:
camera.lookAt(mesh.position) 物体在网格中间,相机视角移动
其中mesh.position,网格位置
camera.lookAt(new THREE.Vector3()) // 这个是移动的物体,不是相机
3.相机距离
mesh.position.distanceTo(new THREE.Vector3(0,1,2)) // 物体距离相机距离
mesh.position.normalize()
mesh.position.length() // 物体距离网格的距离
// normalize设置时将会得到控制台网格距离 且是1
总结
无