移动相机

更新时间: 2021-08-31 17:45:27

可以创建一段曲线,然后在render()中实时的改变摄像头的位置,我说得比较简单。。但是实际上比较复杂

  import * as THREE from 'three/build/three.module.js';
  import * as dat from '../../@js/dat.gui.js'
  import Stats from '../../@js/stats.js'
  import { Curves } from 'three/examples/jsm/curves/CurveExtras.js';
  import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'

  const {GUI} = dat
  console.log(GUI)
  let container, stats

  let camera, scene, renderer, splineCamera, cameraHelper, cameraEye

  const direction = new THREE.Vector3()
  const binormal = new THREE.Vector3()
  const normal = new THREE.Vector3()
  const position = new THREE.Vector3()
  const lookAt = new THREE.Vector3()

  //根据这些点创建一条平滑的三维曲线
  const pipeSpline = new THREE.CatmullRomCurve3([
    new THREE.Vector3( 0, 10, - 10 ), new THREE.Vector3( 10, 0, - 10 ),
    new THREE.Vector3( 20, 0, 0 ), new THREE.Vector3( 30, 0, 10 ),
    new THREE.Vector3( 30, 0, 20 ), new THREE.Vector3( 20, 0, 30 ),
    new THREE.Vector3( 10, 0, 30 ), new THREE.Vector3( 0, 0, 30 ),
    new THREE.Vector3( - 10, 10, 30 ), new THREE.Vector3( - 10, 20, 30 ),
    new THREE.Vector3( 0, 30, 30 ), new THREE.Vector3( 10, 30, 30 ),
    new THREE.Vector3( 20, 30, 15 ), new THREE.Vector3( 10, 30, 10 ),
    new THREE.Vector3( 0, 30, 10 ), new THREE.Vector3( - 10, 20, 10 ),
    new THREE.Vector3( - 10, 10, 10 ), new THREE.Vector3( 0, 0, 10 ),
    new THREE.Vector3( 10, - 10, 10 ), new THREE.Vector3( 20, - 15, 10 ),
    new THREE.Vector3( 30, - 15, 10 ), new THREE.Vector3( 40, - 15, 10 ),
    new THREE.Vector3( 50, - 15, 10 ), new THREE.Vector3( 60, 0, 10 ),
    new THREE.Vector3( 70, 0, 0 ), new THREE.Vector3( 80, 0, 0 ),
    new THREE.Vector3( 90, 0, 0 ), new THREE.Vector3( 100, 0, 0 )
  ])

  const sampleClosedSpline = new THREE.CatmullRomCurve3([
    new THREE.Vector3( 0, - 40, - 40 ),
    new THREE.Vector3( 0, 40, - 40 ),
    new THREE.Vector3( 0, 140, - 40 ),
    new THREE.Vector3( 0, 40, 40 ),
    new THREE.Vector3( 0, - 40, 40 )
  ])

  sampleClosedSpline.curveType = 'catmullrom';
	sampleClosedSpline.closed = true;

  //这里是一些曲线的集合
  const splines = {
    GrannyKnot: new Curves.GrannyKnot(),
    HeartCurve: new Curves.HeartCurve( 3.5 ),
    VivianiCurve: new Curves.VivianiCurve( 70 ),
    KnotCurve: new Curves.KnotCurve(),
    HelixCurve: new Curves.HelixCurve(),
    TrefoilKnot: new Curves.TrefoilKnot(),
    TorusKnot: new Curves.TorusKnot( 20 ),
    CinquefoilKnot: new Curves.CinquefoilKnot( 20 ),
    TrefoilPolynomialKnot: new Curves.TrefoilPolynomialKnot( 14 ),
    FigureEightPolynomialKnot: new Curves.FigureEightPolynomialKnot(),
    DecoratedTorusKnot4a: new Curves.DecoratedTorusKnot4a(),
    DecoratedTorusKnot4b: new Curves.DecoratedTorusKnot4b(),
    DecoratedTorusKnot5a: new Curves.DecoratedTorusKnot5a(),
    DecoratedTorusKnot5c: new Curves.DecoratedTorusKnot5c(),
    PipeSpline: pipeSpline,
    SampleClosedSpline: sampleClosedSpline
  }

  let parent, tubeGeometry, mesh

  const params = {
    spline: 'GrannyKnot',
    scale: 4,
    extrusionSegments: 100,
    radiusSegements: 3,
    closed: true,
    animationView: false,
    lookAhead: false,
    cameraHelper: false
  }

  const material = new THREE.MeshLambertMaterial({ color: 0xff00ff })

  const wireframeMaterial = new THREE.MeshBasicMaterial( { color: 0x000000, opacity: 0.3, wireframe: true, transparent: true } )

  function addTube() {
    if( mesh !== undefined ) {
      parent.remove(mesh)
      mesh.geometry.dispose()
    }
    const extrudePath = splines[params.spline]

    tubeGeometry = new THREE.TubeGeometry( extrudePath, params.extrusionSegments, 2, params.radiusSegements, params.closed)

    addGeometry( tubeGeometry )

    setScale()
  }

  function setScale() {
    mesh.scale.set( params.scale, params.scale, params.scale)
  }

  function addGeometry( geometry ) {
    mesh = new THREE.Mesh(geometry, material)
    const wireframe = new THREE.Mesh(geometry, wireframeMaterial)
    mesh.add(wireframe)

    parent.add(mesh)
  }

  function animateCamera() {
    cameraHelper.visible = params.cameraHelper
    cameraEye.visible = params.cameraHelper
  }

  function init() {
    container = document.getElementById('three1')

    //camera
    camera = new THREE.PerspectiveCamera( 50, container.clientWidth / container.clientHeight, 0.01, 10000)
    camera.position.set(0, 50, 500)

    //scene
    scene = new THREE.Scene()
    scene.background = new THREE.Color(0xf0f0f0)

    //light
    const light = new THREE.DirectionalLight( 0xffffff )
    light.position.set(0,0,1)
    scene.add(light)

    //tube
    parent = new THREE.Object3D()
    scene.add(parent)

    splineCamera = new THREE.PerspectiveCamera(84, container.clientWidth / container.clientHeight, 0.01, 1000)
    parent.add(splineCamera)

    cameraHelper = new THREE.CameraHelper(splineCamera)
    scene.add(cameraHelper)

    addTube()

    // debug camera
    cameraEye = new THREE.Mesh( new THREE.SphereGeometry(5), new THREE.MeshBasicMaterial({color: 0xdddddd}))
    parent.add(cameraEye)

    cameraHelper.visible = params.cameraHelper
    cameraEye.visible = params.cameraHelper

    //renderer
    renderer = new THREE.WebGLRenderer({antialias: true})
    renderer.setPixelRatio(window.devicePixcelRatio)
    renderer.setSize(container.clientWidth, container.clientHeight)
    container.appendChild(renderer.domElement)

    //stats
    stats = new Stats()
    container.appendChild(stats.dom)

    //dat.GUI
    const gui = new GUI({width:300}, container)

    const folderGeometry =  gui.addFolder('Geometry')
    folderGeometry.add(params, 'spline', Object.keys(splines)).onChange(function () {
      addTube()
    })

    folderGeometry.add(params, 'scale',2,10).step(2).onChange(function() {
      setScale()
    })

    folderGeometry.add(params, 'extrusionSegments', 50, 500).step(50).onChange(function() {
      addTube()
    })

    folderGeometry.add(params, 'radiusSegements',2, 12).step(1).onChange(function() {
      addTube()
    })

    folderGeometry.add(params,'closed').onChange(function() {
      addTube()
    })
    folderGeometry.open()

    const folderCamera = gui.addFolder('Camera')
    folderCamera.add(params, 'animationView').onChange(function() {
      animateCamera()
    })

    folderCamera.add(params, 'lookAhead').onChange(function() {
      animateCamera()
    })

    folderCamera.add(params, 'cameraHelper').onChange(function() {
      animateCamera()
    })

    folderCamera.open()

    const controls = new OrbitControls(camera, renderer.domElement)
    controls.minDistance = 100
    controls.maxDistance = 2000
  }

  function animate() {
    requestAnimationFrame(animate)
    render()
    stats.update()
  }

  function render(){
    //animate camera along spline
    const time = Date.now()
    const looptime = 20 * 1000 
    const t = (time % looptime) / looptime //这里的t相当于是一个百分比的位置

    //取当前时间节点的点的位置
    tubeGeometry.parameters.path.getPointAt(t,position)
    //将向量position与标量scale相乘,得到新的位置
    position.multiplyScalar(params.scale)

    //interpolation
    //tangents是切线数组
    const segements = tubeGeometry.tangents.length

    // 得到当前时间所在的法线分段
    const pickt = t * segements 

    //向下取整
    const pick = Math.floor(pickt) 

    //得到下一个pick的位置,之所以要取余是担心到最后一个位置了再加一溢出
    const pickNext = ( pick + 1 ) % segements 

    //两个位置的次法线向量相减
    binormal.subVectors( tubeGeometry.binormals[pickNext], tubeGeometry.binormals[pick])
    //得到当前位置的次法线,让过渡平滑
    binormal.multiplyScalar(pickt - pick).add(tubeGeometry.binormals[pick]) 

    //得到当前时间点的切线方向
    tubeGeometry.parameters.path.getTangentAt(t, direction) 
    const offset = 15

    //将次法线和切线 叉乘 得到主法线
    normal.copy(binormal).cross(direction) 

    //we move on a offset on its binormal
    //让位置沿着法线移动一点点距离
    position.add(normal.clone().multiplyScalar(offset)) 

    splineCamera.position.copy(position)
    cameraEye.position.copy(position)

    // using arcLength for stablization in look ahead  利用弧长稳定看向前方
    //获取到前方的位置
    tubeGeometry.parameters.path.getPointAt((t + 30 / tubeGeometry.parameters.path.getLength()) % 1, lookAt) 
    lookAt.multiplyScalar(params.scale) //记得也要乘以系数

    // camera orientation 2 - up orientaion via normal

    if(!params.lookAhead) {
      lookAt.copy(position).add(direction) //如果不需要一直向前看,那就看切线方向
    }

    //构造一个旋转矩阵,从splineCamera.position 指向 loolAt, 由向量 normal 定向。 也就是设定摄像机的位置
    splineCamera.matrix.lookAt(splineCamera.position, lookAt, normal) 
    splineCamera.quaternion.setFromRotationMatrix(splineCamera.matrix) //旋转摄像机角度

    cameraHelper.update()

    renderer.render(scene, params.animationView === true ? splineCamera : camera) //切换相机

  }


  init()
  animate()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278