找物源码导读Cocos Creator 3.8 · assets/scripts
0%
已读 0 / 424
目录— 个文件
目录加载中…
…/module/component/PageSnapComponent.ts
1/**
2 * 通用分页吸附组件
3 *
4 * 设计目标:
5 * - 固定 2 个物理 page 节点(active + buffer),通过复用承载全部逻辑页
6 * - 支持横向 / 纵向两种方向,统一使用“主轴/副轴”手势模型
7 * - 尽量沿用 ScrollView 的输入哲学,而不是自己模拟点击分发
8 *
9 * 输入模型:
10 * - 像 ScrollView 一样在容器节点上以“捕获阶段”监听 TOUCH_START/MOVE/END/CANCEL
11 * - 子节点可以继续挂 Button 或监听 node.on('click')
12 * - 当手势尚未确认是拖拽前,不干预子节点点击链
13 * - 当手势被判定为分页拖拽后,主动向最初的触摸目标派发模拟 TOUCH_CANCEL
14 * - 这样 Button 会自然取消点击,而不是由分页组件自己 triggerTap
15 *
16 * item 接入约定:
17 * - item 内部仍然可以使用 Button / click 事件
18 * - 不需要向分页组件注册点击目标,也不需要做事件转发
19 * - 若业务想保留独立的命中查询工具,可在 page/item 组件里自行保留,不参与输入主链
20 */
21
22import { _decorator, Component, Node, UITransform, Prefab, instantiate, EventTouch, Tween, tween, Vec3, TweenEasing, Enum } from 'cc';
23import { PageSnapDirection, PageSnapTuning, PageSnapTuningPreset, PAGE_SNAP_TUNING_TABLE } from './PageSnapDefine';
24const { ccclass, property } = _decorator;
25
26@ccclass('PageSnapComponent')
27export class PageSnapComponent extends Component {
28 private static readonly PAGE_NODE_COUNT = 2;
29
30 @property({ type: Node, tooltip: '可视区域节点' })
31 viewport: Node = null!;
32
33 @property({ type: Node, tooltip: '页面内容容器节点' })
34 content: Node = null!;
35
36 @property({ type: Prefab, tooltip: '页面预制体' })
37 pagePrefab: Prefab = null!;
38
39 @property({ type: Enum(PageSnapDirection), tooltip: '分页方向' })
40 scrollDirection: PageSnapDirection = PageSnapDirection.Horizontal;
41
42 @property({ type: Enum(PageSnapTuningPreset), tooltip: '手感参数表选择' })
43 tuningPreset: PageSnapTuningPreset = PageSnapTuningPreset.Balanced;
44
45 @property({ tooltip: '像 ScrollView 一样,在确认拖拽后取消子节点触摸事件' })
46 cancelInnerEvents: boolean = true;
47
48 /** page 节点创建后回调,业务层通常在这里做首屏灌数。 */
49 public onPageNodeReady: ((pageIdx: number, node: Node) => void) | null = null;
50 /** 即将切到目标页时回调,业务层可在这里把目标页数据灌进 buffer。 */
51 public onPageWillChange: ((page: number, pageIdx: number, direction: 1 | -1) => void) | null = null;
52 /** 翻页动画结束后回调,业务层可在这里同步页码与预热下一张 buffer 页。 */
53 public onPageChanged: ((page: number, bufPage: number, bufPositive: boolean) => void) | null = null;
54
55 /** 运行时 page 节点池:[0]=active, [1]=buffer。 */
56 private _pages: Array<Node | null> = [null, null];
57 private _pageTweens: Tween<any>[] = [];
58 public get pageNodes(): Node[] { return this._pages.filter((page): page is Node => page !== null); }
59
60 private _curPage: number = 0;
61 private _total: number = 0;
62 private _viewportSize: number = 0;
63 private _pageSize: number = 0;
64 private _lock: boolean = false;
65 private _active: 0 | 1 = 0;
66 /** buffer 是否位于“翻页正方向”一侧。横向时正方向=右侧;纵向时正方向=下侧。 */
67 private _bufferPositive: boolean = true;
68 private _built: boolean = false;
69 private _dragging: boolean = false;
70 /** 手势主轴起点。横向时为 x,纵向时为 y。 */
71 private _touchStartPrimary: number = 0;
72 /** 手势副轴起点。横向时为 y,纵向时为 x。 */
73 private _touchStartSecondary: number = 0;
74 private _rawDragDeltaPrimary: number = 0;
75 private _dragDeltaPrimary: number = 0;
76 private _dragDirection: -1 | 0 | 1 = 0;
77 private _dragTargetPage: number = -1;
78 private _lastMovePrimary: number = 0;
79 private _lastMoveTime: number = 0;
80 private _velocityPrimary: number = 0;
81 private _activeTouchId: number = -1;
82 private _dragCaptured: boolean = false;
83 /** 本轮触摸开始时的原始目标节点,用于在确认拖拽后派发模拟 TOUCH_CANCEL。 */
84 private _initialTouchTarget: Node | null = null;
85 /** 是否已经向原始目标派发过模拟 TOUCH_CANCEL。 */
86 private _innerEventCanceled: boolean = false;
87 /** 手势方向锁:-1=副轴,0=未决,1=主轴。 */
88 private _gestureAxisLock: -1 | 0 | 1 = 0;
89 private _tuning: PageSnapTuning = PAGE_SNAP_TUNING_TABLE[PageSnapTuningPreset.Balanced];
90
91 public get ActiveIdx(): number { return this._active; }
92 public get CurrentPage(): number { return this._curPage; }
93 public get TotalPages(): number { return this._total; }
94
95 /** 初始化分页器;只创建 2 个物理页节点并准备第一页。 */
96 public Init(total: number, start: number): void {
97 this.ApplyTuningPreset();
98 this._total = total;
99 this._curPage = start;
100 this._viewportSize = this.GetViewportSize();
101 this._active = 0;
102 this._bufferPositive = true;
103 this.ResetRuntimeState();
104 this.content?.setPosition(0, 0, 0);
105 this.StopPageTweens();
106
107 if (!this._built) {
108 this.EnsurePageNode(0);
109 this.WarmupBufferPage();
110 this._built = true;
111 } else {
112 this.EnsurePageNode(0);
113 this.EnsurePageNode(1);
114 }
115
116 const contentTransform = this.content?.getComponent(UITransform);
117 if (!contentTransform) return;
118 if (this.scrollDirection === PageSnapDirection.Horizontal) {
119 contentTransform.width = this._viewportSize + this._pageSize * 2;
120 } else {
121 contentTransform.height = this._viewportSize + this._pageSize * 2;
122 }
123
124 this.SetPageOffset(0, 0);
125 this.SetPageOffset(1, this.GetBufferBaseOffset(true));
126 this.RegisterTouchEvents();
127 }
128
129 /** 程序化跳页入口;按钮翻页、快捷跳 10 页都应通过这里调用。 */
130 public GoToPage(target: number): void {
131 if (this._lock || target === this._curPage || target < 0 || target >= this._total) return;
132 this.DoTurn(target, target > this._curPage ? 1 : -1);
133 }
134
135 /** 关闭面板时释放事件与 tween,但保留已创建的物理页节点用于后续复用。 */
136 public DeInit(): void {
137 this.UnregisterTouchEvents();
138 this.StopPageTweens();
139 this.unscheduleAllCallbacks();
140 this.ResetRuntimeState();
141 }
142
143 /** 获取指定物理页节点,供业务层向该页灌入数据。 */
144 public GetPageNode(index: number): Node | null {
145 return this._pages[index] ?? null;
146 }
147
148 /** 供业务层判断本轮手势是否已被分页拖拽接管。 */
149 public HasCapturedDrag(): boolean {
150 return this._dragCaptured;
151 }
152
153 /** 次帧预热 buffer 页,避免首开把两页实例化成本压在同一帧。 */
154 private WarmupBufferPage(): void {
155 if (this._total <= 1) return;
156 this.scheduleOnce(() => {
157 if (!this.node?.isValid) return;
158 this.EnsurePageNode(1);
159 }, 0);
160 }
161
162 /** 确保指定索引的物理页存在;不存在时实例化并摆到正确的 buffer 位置。 */
163 private EnsurePageNode(index: number): Node | null {
164 if (index < 0 || index >= PageSnapComponent.PAGE_NODE_COUNT || !this.pagePrefab || !this.content) return null;
165 const existed = this._pages[index];
166 if (existed?.isValid) {
167 return existed;
168 }
169
170 const node = instantiate(this.pagePrefab);
171 node.setParent(this.content);
172 this._pages[index] = node;
173
174 if (this._pageSize <= 0) {
175 const transform = node.getComponent(UITransform);
176 this._pageSize = this.scrollDirection === PageSnapDirection.Horizontal
177 ? (transform?.width ?? 0)
178 : (transform?.height ?? 0);
179 }
180
181 const offset = index === this._active ? 0 : this.GetBufferBaseOffset(this._bufferPositive);
182 this.SetPageOffset(index, offset);
183 this.onPageNodeReady?.(index, node);
184 return node;
185 }
186
187 /** 注册容器级触摸监听。这里像 ScrollView 一样使用捕获阶段先接管输入。 */
188 private RegisterTouchEvents(): void {
189 this.UnregisterTouchEvents();
190 this.node.on(Node.EventType.TOUCH_START, this.OnTouchStart, this, true);
191 this.node.on(Node.EventType.TOUCH_MOVE, this.OnTouchMove, this, true);
192 this.node.on(Node.EventType.TOUCH_END, this.OnTouchEnd, this, true);
193 this.node.on(Node.EventType.TOUCH_CANCEL, this.OnTouchCancel, this, true);
194 }
195
196 private UnregisterTouchEvents(): void {
197 this.node.off(Node.EventType.TOUCH_START, this.OnTouchStart, this, true);
198 this.node.off(Node.EventType.TOUCH_MOVE, this.OnTouchMove, this, true);
199 this.node.off(Node.EventType.TOUCH_END, this.OnTouchEnd, this, true);
200 this.node.off(Node.EventType.TOUCH_CANCEL, this.OnTouchCancel, this, true);
201 }
202
203 private OnTouchStart(event: EventTouch): void {
204 this.BeginGesture(event);
205 }
206
207 private OnTouchMove(event: EventTouch): void {
208 this.UpdateGesture(event);
209 }
210
211 private OnTouchEnd(event: EventTouch): void {
212 this.EndGesture(event, false);
213 }
214
215 private OnTouchCancel(event: EventTouch): void {
216 this.EndGesture(event, true);
217 }
218
219 /** 触摸开始:记录起点和原始触摸目标,先不干预子节点点击链。 */
220 private BeginGesture(event: EventTouch): void {
221 if (this._lock || this._total <= 1) return;
222 const touchId = event.touch?.getID?.() ?? event.getID?.() ?? 0;
223 if (this._dragging && this._activeTouchId === touchId) return;
224
225 const location = event.getUILocation();
226 this._dragging = true;
227 this._activeTouchId = touchId;
228 this._dragCaptured = false;
229 this._gestureAxisLock = 0;
230 this._touchStartPrimary = this.GetPrimaryValue(location.x, location.y);
231 this._touchStartSecondary = this.GetSecondaryValue(location.x, location.y);
232 this._rawDragDeltaPrimary = 0;
233 this._dragDeltaPrimary = 0;
234 this._dragDirection = 0;
235 this._dragTargetPage = -1;
236 this._lastMovePrimary = this._touchStartPrimary;
237 this._lastMoveTime = performance.now();
238 this._velocityPrimary = 0;
239 this._initialTouchTarget = this.ResolveInitialTouchTarget(event);
240 this._innerEventCanceled = false;
241 this.StopPageTweens();
242 this.StopPropagationIfTargetIsMe(event);
243 }
244
245 /** 触摸移动:先判方向锁;一旦确认拖拽,就取消原始 target 的点击链。 */
246 private UpdateGesture(event: EventTouch): void {
247 if (!this._dragging || this._lock) return;
248 const touchId = event.touch?.getID?.() ?? event.getID?.() ?? 0;
249 if (this._activeTouchId !== -1 && touchId !== this._activeTouchId) return;
250
251 const location = event.getUILocation();
252 const primary = this.GetPrimaryValue(location.x, location.y);
253 const secondary = this.GetSecondaryValue(location.x, location.y);
254 const rawPrimary = primary - this._touchStartPrimary;
255 const rawSecondary = secondary - this._touchStartSecondary;
256 const absPrimary = Math.abs(rawPrimary);
257 const absSecondary = Math.abs(rawSecondary);
258 const now = performance.now();
259 this.UpdateVelocity(primary, now);
260
261 if (this._gestureAxisLock === 0) {
262 const canLockPrimary = absPrimary >= this._tuning.horizontalLockStartDistance
263 && absPrimary >= absSecondary * this._tuning.horizontalLockRatio;
264 const shouldRejectAsSecondary = absSecondary >= this._tuning.verticalNoiseTolerance
265 && absSecondary > absPrimary * this._tuning.horizontalLockRatio;
266
267 if (canLockPrimary) {
268 this._gestureAxisLock = 1;
269 this._dragCaptured = true;
270 this.CancelInnerTouchEvents(event);
271 } else if (shouldRejectAsSecondary) {
272 this._gestureAxisLock = -1;
273 return;
274 } else {
275 return;
276 }
277 }
278
279 if (this._gestureAxisLock === -1) {
280 return;
281 }
282
283 event.propagationStopped = true;
284
285 const direction = this.ResolvePageDirection(rawPrimary);
286 const targetPage = this._curPage + direction;
287 const hasTarget = direction !== 0 && targetPage >= 0 && targetPage < this._total;
288 const targetChanged = this._dragTargetPage !== targetPage || this._dragDirection !== direction;
289
290 this._dragDirection = direction;
291 this._rawDragDeltaPrimary = rawPrimary;
292 this._dragDeltaPrimary = hasTarget ? this.MapFollowDelta(rawPrimary) : this.MapEdgeDelta(rawPrimary);
293
294 if (hasTarget) {
295 this.PrepareDragTarget(targetPage, direction, targetChanged);
296 this._dragTargetPage = targetPage;
297 this.ApplyDragOffset(this._dragDeltaPrimary, direction > 0);
298 return;
299 }
300
301 this._dragTargetPage = -1;
302 this.ApplyEdgeDragOffset(this._dragDeltaPrimary);
303 }
304
305 /** 触摸结束:若本轮已进入拖拽,则阻断 end 继续传播,让 Button 不再触发 click。 */
306 private EndGesture(event?: EventTouch, canceled: boolean = false): void {
307 if (canceled && (event as any)?.simulate) {
308 return;
309 }
310
311 this.CompleteDragGesture();
312 if (!event) {
313 return;
314 }
315
316 if (this._dragCaptured) {
317 event.propagationStopped = true;
318 } else {
319 this.StopPropagationIfTargetIsMe(event);
320 }
321 }
322
323 /** 当前手势收尾。只有锁定为主轴拖拽后才会真正触发分页动画。 */
324 private CompleteDragGesture(): void {
325 if (!this._dragging || this._lock) return;
326 this._dragging = false;
327
328 if (this._gestureAxisLock !== 1 || !this._dragCaptured) {
329 this.ResetRuntimeState();
330 return;
331 }
332
333 const distanceThreshold = Math.max(16, this._viewportSize * this._tuning.turnDistanceRatio);
334 const absDistance = Math.abs(this._rawDragDeltaPrimary);
335 const absVelocity = Math.abs(this._velocityPrimary);
336 const shouldTurnByDistance = absDistance >= distanceThreshold;
337 const shouldTurnByVelocity = absDistance >= this._tuning.flingMinDistance && absVelocity >= this._tuning.flingVelocity;
338 const shouldTurn = this._dragTargetPage >= 0
339 && this._dragDirection !== 0
340 && (shouldTurnByDistance || shouldTurnByVelocity);
341
342 if (shouldTurn) {
343 this.DoTurn(this._dragTargetPage, this._dragDirection);
344 return;
345 }
346
347 this.SnapBack(this._dragDirection > 0 ? true : this._bufferPositive);
348 }
349
350 /** 开始一次翻页;会先确保目标 buffer 已就位,再播放离场/进场动画。 */
351 private DoTurn(target: number, delta: number): void {
352 this._lock = true;
353 const forward = delta > 0;
354 const currentActive = this._active;
355 const nextActive = this._active === 0 ? 1 : 0;
356 const alreadyPrepared = this._dragTargetPage === target && this._dragDirection === delta;
357 this.EnsurePageNode(nextActive);
358 if (forward !== this._bufferPositive) {
359 this._bufferPositive = forward;
360 this.SetPageOffset(nextActive, this.GetBufferBaseOffset(forward));
361 }
362 if (!alreadyPrepared) {
363 this.onPageWillChange?.(target, nextActive, forward ? 1 : -1);
364 }
365 this._active = nextActive;
366 this.AnimateTurn(currentActive, nextActive, target, forward);
367 }
368
369 /** 拖拽阶段预装目标页,并把 buffer 放到正确一侧。 */
370 private PrepareDragTarget(targetPage: number, direction: -1 | 1, targetChanged: boolean): void {
371 const nextActive = this._active === 0 ? 1 : 0;
372 const forward = direction > 0;
373 this.EnsurePageNode(nextActive);
374
375 if (targetChanged || this._bufferPositive !== forward) {
376 this._bufferPositive = forward;
377 this.SetPageOffset(nextActive, this.GetBufferBaseOffset(forward));
378 this.onPageWillChange?.(targetPage, nextActive, direction);
379 }
380 }
381
382 /** 翻页结束后的状态收敛。 */
383 private Finish(newPage: number, forward: boolean): void {
384 this._curPage = newPage;
385 this.SetPageOffset(this._active, 0);
386 const other = this._active === 0 ? 1 : 0;
387 this._bufferPositive = forward;
388 this.SetPageOffset(other, this.GetBufferBaseOffset(forward));
389 this.ResetRuntimeState();
390 const bp = forward ? newPage + 1 : newPage - 1;
391 this.onPageChanged?.(newPage, bp, forward);
392 this._lock = false;
393 }
394
395 /** 播放当前页离场 + buffer 页入场动画。 */
396 private AnimateTurn(currentActive: 0 | 1, nextActive: 0 | 1, target: number, forward: boolean): void {
397 const currentTargetOffset = this.GetExitTargetOffset(forward);
398 const nextTargetOffset = 0;
399 const remainingDistance = Math.max(
400 Math.abs(this.GetPageOffset(currentActive) - currentTargetOffset),
401 Math.abs(this.GetPageOffset(nextActive) - nextTargetOffset),
402 );
403 const duration = this.ResolveTurnDuration(remainingDistance, Math.abs(this._velocityPrimary));
404 this.StopPageTweens();
405 this.TweenPageOffset(currentActive, currentTargetOffset, duration, 'quartOut');
406 this.TweenPageOffset(nextActive, nextTargetOffset, duration, 'quartOut', () => {
407 this.Finish(target, forward);
408 });
409 }
410
411 /** 未达到翻页条件时回弹到当前页。 */
412 private SnapBack(bufferPositive: boolean): void {
413 this._lock = true;
414 const activeIdx = this._active;
415 const bufferIdx = activeIdx === 0 ? 1 : 0;
416 this._bufferPositive = bufferPositive;
417 this.StopPageTweens();
418 this.TweenPageOffset(activeIdx, 0, this._tuning.snapBackDuration, 'quadOut');
419 this.TweenPageOffset(bufferIdx, this.GetBufferBaseOffset(bufferPositive), this._tuning.snapBackDuration, 'quadOut', () => {
420 this.ResetRuntimeState();
421 this._lock = false;
422 });
423 }
424
425 /** 拖拽中同时移动 active 与 buffer,形成整页跟手效果。 */
426 private ApplyDragOffset(delta: number, bufferPositive: boolean): void {
427 const activeIdx = this._active;
428 const bufferIdx = activeIdx === 0 ? 1 : 0;
429 const bufferBase = this.GetBufferBaseOffset(bufferPositive);
430 this.SetPageOffset(activeIdx, delta);
431 this.SetPageOffset(bufferIdx, bufferBase + delta);
432 }
433
434 /** 边界页无相邻逻辑页时,只对当前页施加橡皮筋阻尼。 */
435 private ApplyEdgeDragOffset(delta: number): void {
436 const activeIdx = this._active;
437 const bufferIdx = activeIdx === 0 ? 1 : 0;
438 this.SetPageOffset(activeIdx, delta);
439 this.SetPageOffset(bufferIdx, this.GetBufferBaseOffset(this._bufferPositive));
440 }
441
442 /** 按当前方向把逻辑偏移量转换成 page 节点坐标并执行 tween。 */
443 private TweenPageOffset(idx: number, offset: number, duration: number, easing: TweenEasing, onComplete?: () => void): void {
444 const node = this._pages[idx];
445 if (!node) {
446 onComplete?.();
447 return;
448 }
449
450 const position = this.MakeAxisPosition(offset);
451 Tween.stopAllByTarget(node);
452 const pt = tween(node)
453 .to(duration, { position }, { easing })
454 .call(() => {
455 const i = this._pageTweens.indexOf(pt);
456 if (i >= 0) this._pageTweens.splice(i, 1);
457 onComplete?.();
458 })
459 .start();
460 this._pageTweens.push(pt);
461 }
462
463 /** 停止所有页节点上的 tween,避免旧动画干扰新手势。 */
464 private StopPageTweens(): void {
465 this._pageTweens.forEach(t => t.stop());
466 this._pageTweens = [];
467 for (const page of this._pages) {
468 if (page) Tween.stopAllByTarget(page);
469 }
470 }
471
472 /** 清空本轮手势临时状态;不会重置当前页和物理页节点本身。 */
473 private ResetRuntimeState(): void {
474 this._rawDragDeltaPrimary = 0;
475 this._dragDeltaPrimary = 0;
476 this._dragDirection = 0;
477 this._dragTargetPage = -1;
478 this._velocityPrimary = 0;
479 this._activeTouchId = -1;
480 this._dragCaptured = false;
481 this._initialTouchTarget = null;
482 this._innerEventCanceled = false;
483 this._gestureAxisLock = 0;
484 this._touchStartPrimary = 0;
485 this._touchStartSecondary = 0;
486 }
487
488 /** 从参数表读取当前 preset 对应的手感配置。 */
489 private ApplyTuningPreset(): void {
490 const preset = PAGE_SNAP_TUNING_TABLE[this.tuningPreset];
491 if (preset) this._tuning = preset;
492 }
493
494 /** 获取主视口在当前方向下的长度。横向取宽,纵向取高。 */
495 private GetViewportSize(): number {
496 const transform = this.viewport?.getComponent(UITransform) ?? this.node.getComponent(UITransform);
497 if (!transform) return 0;
498 return this.scrollDirection === PageSnapDirection.Horizontal ? transform.width : transform.height;
499 }
500
501 /** 把屏幕坐标映射为主轴坐标。横向时主轴=x,纵向时主轴=y。 */
502 private GetPrimaryValue(x: number, y: number): number {
503 return this.scrollDirection === PageSnapDirection.Horizontal ? x : y;
504 }
505
506 /** 把屏幕坐标映射为副轴坐标。横向时副轴=y,纵向时副轴=x。 */
507 private GetSecondaryValue(x: number, y: number): number {
508 return this.scrollDirection === PageSnapDirection.Horizontal ? y : x;
509 }
510
511 /** 根据主轴位移推导翻页方向。返回值语义:1=翻向下一页,-1=翻向上一页。 */
512 private ResolvePageDirection(rawPrimary: number): -1 | 0 | 1 {
513 if (this.scrollDirection === PageSnapDirection.Horizontal) {
514 return rawPrimary < 0 ? 1 : rawPrimary > 0 ? -1 : 0;
515 }
516 return rawPrimary > 0 ? 1 : rawPrimary < 0 ? -1 : 0;
517 }
518
519 /** 获取 buffer 页的停靠基准位置。 */
520 private GetBufferBaseOffset(forward: boolean): number {
521 if (this.scrollDirection === PageSnapDirection.Horizontal) {
522 return forward ? this._viewportSize : -this._viewportSize;
523 }
524 return forward ? -this._viewportSize : this._viewportSize;
525 }
526
527 /** 获取当前页离场时的终点位置。 */
528 private GetExitTargetOffset(forward: boolean): number {
529 if (this.scrollDirection === PageSnapDirection.Horizontal) {
530 return forward ? -this._viewportSize : this._viewportSize;
531 }
532 return forward ? this._viewportSize : -this._viewportSize;
533 }
534
535 /** 给指定物理页设置当前方向下的逻辑偏移。 */
536 private SetPageOffset(idx: number, offset: number): void {
537 this._pages[idx]?.setPosition(this.MakeAxisPosition(offset));
538 }
539
540 /** 读取指定物理页在当前方向下的逻辑偏移。 */
541 private GetPageOffset(idx: number): number {
542 const page = this._pages[idx];
543 if (!page) return 0;
544 return this.scrollDirection === PageSnapDirection.Horizontal ? page.position.x : page.position.y;
545 }
546
547 /** 把当前方向下的逻辑偏移转换成 Vec3 位置。 */
548 private MakeAxisPosition(offset: number): Vec3 {
549 return this.scrollDirection === PageSnapDirection.Horizontal
550 ? new Vec3(offset, 0, 0)
551 : new Vec3(0, offset, 0);
552 }
553
554 /** 使用指数平滑估算主轴速度,供 fling 判定与动画时长估算使用。 */
555 private UpdateVelocity(currentPrimary: number, now: number): void {
556 const deltaTimeMs = now - this._lastMoveTime;
557 if (deltaTimeMs <= 0) {
558 this._lastMovePrimary = currentPrimary;
559 this._lastMoveTime = now;
560 return;
561 }
562
563 const delta = currentPrimary - this._lastMovePrimary;
564 const sampleVelocity = (delta / deltaTimeMs) * 1000;
565 this._velocityPrimary = (this._velocityPrimary * 0.35) + (sampleVelocity * 0.65);
566 this._lastMovePrimary = currentPrimary;
567 this._lastMoveTime = now;
568 }
569
570 /** 正常拖拽时的主轴位移映射:前段跟手,超出软区后渐进阻尼。 */
571 private MapFollowDelta(rawDelta: number): number {
572 const absDelta = Math.abs(rawDelta);
573 const softZone = this._viewportSize * this._tuning.followSoftZoneRatio;
574 if (absDelta <= softZone) {
575 return rawDelta;
576 }
577
578 const sign = rawDelta >= 0 ? 1 : -1;
579 const damped = softZone + ((absDelta - softZone) * this._tuning.followDamping);
580 const maxFollow = this._viewportSize * 0.92;
581 return sign * Math.min(damped, maxFollow);
582 }
583
584 /** 边界拖拽时的位移映射:使用橡皮筋阻尼,防止硬顶。 */
585 private MapEdgeDelta(rawDelta: number): number {
586 const sign = rawDelta >= 0 ? 1 : -1;
587 const absDelta = Math.abs(rawDelta);
588 const ratio = absDelta / Math.max(1, this._viewportSize);
589 const mapped = this._viewportSize * (1 - (1 / (1 + (ratio * this._tuning.edgeResistance))));
590 return sign * mapped;
591 }
592
593 /** 按剩余距离和释放速度估算翻页动画时长。 */
594 private ResolveTurnDuration(remainingDistance: number, releaseVelocity: number): number {
595 const distanceRatio = Math.max(0, Math.min(1, remainingDistance / Math.max(1, this._viewportSize)));
596 const velocityBoost = Math.max(0, Math.min(1, releaseVelocity / Math.max(this._tuning.flingVelocity, 1)));
597 const base = this._tuning.turnMaxDuration - ((this._tuning.turnMaxDuration - this._tuning.turnMinDuration) * distanceRatio * 0.7);
598 const boosted = base - ((base - this._tuning.turnMinDuration) * velocityBoost * 0.5);
599 return Math.max(this._tuning.turnMinDuration, Math.min(this._tuning.turnMaxDuration, boosted));
600 }
601
602 /** 获取本轮触摸开始时的原始目标节点,仅接受 active page 内部的节点。 */
603 private ResolveInitialTouchTarget(event: EventTouch): Node | null {
604 const activeNode = this._pages[this._active];
605 const eventTarget = event.target as Node | null;
606 if (!activeNode || !eventTarget) {
607 return null;
608 }
609
610 let current: Node | null = eventTarget;
611 while (current) {
612 if (current === activeNode) {
613 return eventTarget;
614 }
615 current = current.parent;
616 }
617 return null;
618 }
619
620 /**
621 * 像 ScrollView 一样,在确认拖拽后向原始 target 派发模拟 TOUCH_CANCEL。
622 *
623 * 这样做的好处:
624 * - Button 会自然取消 click,而不是由分页器自己模拟点击
625 * - 任何依赖 TOUCH_CANCEL / click 的子节点都能沿用原生输入模型
626 */
627 private CancelInnerTouchEvents(event: EventTouch): void {
628 if (!this.cancelInnerEvents || this._innerEventCanceled || !this._initialTouchTarget) {
629 return;
630 }
631 if (this._initialTouchTarget === this.node) {
632 return;
633 }
634
635 const cancelEvent = new EventTouch(event.getTouches(), event.bubbles, Node.EventType.TOUCH_CANCEL);
636 cancelEvent.touch = event.touch;
637 (cancelEvent as any).simulate = true;
638 this._initialTouchTarget.dispatchEvent(cancelEvent);
639 this._innerEventCanceled = true;
640 }
641
642 /**
643 * 与 ScrollView 保持一致:
644 * - 当事件真正命中当前分页器节点自身时,阻断它继续冒泡给父级 Button
645 * - 若事件命中的是子节点,则允许其原生点击链继续存在
646 */
647 private StopPropagationIfTargetIsMe(event: EventTouch): void {
648 if (event.eventPhase === EventTouch.AT_TARGET && event.target === this.node) {
649 event.propagationStopped = true;
650 }
651 }
652}
讲解653 行
双页吸附人工通读

PageSnapComponent.ts

业务调用 Init 建立两张可复用物理页,通过准备页和完成页回调填充逻辑页内容。组件保存页码、双页位置与手势状态,捕获触摸后按主副轴锁定并模拟取消子点击;DeInit 保留节点,当前物理页索引在动画开始时就交换,逻辑页码到结束才更新。

从 Init 和三个回调接入点开始,再顺着 BeginGesture、UpdateGesture、CompleteDragGesture 到 Finish。

特殊处理与易错点

  • 时序首次 buffer 延迟到次帧实例化;立即翻页也会主动补建。
27注释PageSnapComponent:通用分页吸附组件 设计目标: - 固定 2 个物理 page 节点(active + buf
31属性viewport(Node):该模块的运行态字段。
34属性content(Node):该模块的运行态字段。
37属性页 Prefab(Prefab):该模块的运行态字段。
40属性scroll Direction(PageSnapDirection):该模块的运行态字段。
43属性tuning Preset(PageSnapTuningPreset):该模块的运行态字段。
46属性cancel Inner 事件(boolean):该模块的运行态字段。
49注释page 节点创建后回调,业务层通常在这里做首屏灌数。
51注释即将切到目标页时回调,业务层可在这里把目标页数据灌进 buffer。
53注释翻页动画结束后回调,业务层可在这里同步页码与预热下一张 buffer 页。
56属性两个物理页槽位,索引不代表逻辑页码。
57属性运行时 page 节点池:[0]=active, [1]=buffer。
58方法过滤掉空槽位后列出当前已经实例化的物理页节点。
60属性动画完成后提交的逻辑页码。
61属性total(number):该模块的运行态字段。
62属性viewport Size(number):该模块的运行态字段。
63属性页 Size(number):该模块的运行态字段。
64属性翻页和回弹期间拒绝新输入,ResetRuntimeState 不重置它。
65属性当前活动物理槽位,在动画开始而非结束时切换。
67属性buffer 是否位于“翻页正方向”一侧。横向时正方向=右侧;纵向时正方向=下侧。
68属性buffer 是否位于“翻页正方向”一侧。横向时正方向=右侧;纵向时正方向=下侧。
69属性buffer 是否位于“翻页正方向”一侧。横向时正方向=右侧;纵向时正方向=下侧。
71属性手势主轴起点。横向时为 x,纵向时为 y。
73属性手势副轴起点。横向时为 y,纵向时为 x。
74属性手势副轴起点。横向时为 y,纵向时为 x。
75属性手势副轴起点。横向时为 y,纵向时为 x。
76属性手势副轴起点。横向时为 y,纵向时为 x。
77属性drag Target 页(number):该模块的运行态字段。
78属性last Move Primary(number):该模块的运行态字段。
79属性last Move 时间(number):计时相关状态,注意切后台与销毁时暂停/清理。
80属性velocity Primary(number):该模块的运行态字段。
81属性active Touch Id(number):该模块的运行态字段。
82属性drag Captured(boolean):该模块的运行态字段。
84属性本轮触摸开始时的原始目标节点,用于在确认拖拽后派发模拟 TOUCH_CANCEL。
86属性是否已经向原始目标派发过模拟 TOUCH_CANCEL。
88属性手势方向锁:-1=副轴,0=未决,1=主轴。
89属性手势方向锁:-1=副轴,0=未决,1=主轴。
91方法读取当前被指定为活动页的物理节点池索引。
92方法读取最近一次完成翻页后保存的逻辑页码。
93方法读取最近一次初始化写入的逻辑页面总数量。
96方法设置逻辑页范围并准备双页节点尺寸位置和触摸监听。
130方法拒绝锁定同页及越界请求后开始目标页翻页动画。
136方法释放触摸动画与调度回调但保留双页节点供复用。
144方法按物理槽位取得已经创建的页面节点供业务灌数。
149方法读取当前手势是否已经被确认为分页主轴拖拽。
154方法存在相邻逻辑页时安排次帧补建缓冲物理页节点。
163方法复用有效物理页或实例化预制体并通知业务灌数。
188方法先卸载旧监听再以捕获阶段注册四类分页触摸事件。
196方法移除分页容器捕获阶段的开始移动结束和取消监听。
203方法把捕获的触摸开始事件交给手势起点采样流程。
207方法把捕获的触摸移动事件交给轴锁与跟手更新流程。
211方法以正常结束方式收拢本轮手势并判定是否翻页。
215方法以取消标志进入手势收尾并过滤自行模拟的取消。
220方法记录触点编号起点原始目标并重置本轮速度与轴锁。
246方法匹配触点后判定主副轴锁定并更新两页跟手位置。
306方法过滤模拟取消后完成拖拽并按捕获标记处理传播。
324方法按原始拖动距离和释放速度决定翻页或回弹。
351方法锁定输入准备目标缓冲页并交换物理活动槽开始动画。
370方法确保缓冲页位于拖动方向一侧并通知业务准备数据。
383方法提交逻辑页码归位双页并回调业务后解除输入锁。
396方法根据剩余距离和速度同时播放旧页离场与新页入场。
412方法锁定输入并把活动页及缓冲页动画恢复至基准位置。
426方法把相同主轴位移应用到活动页和相邻缓冲页。
435方法没有相邻逻辑页时只移动活动页而让缓冲页停靠。
443方法停止目标页已有动画并记录新的轴向位置过渡动画。
464方法停止记录动画并额外停止每个物理页上的全部动画。
473方法清空本轮手势采样轴锁和触摸目标而保留页码锁值。
489方法从共享参数表取出当前预设并保存其配置引用。
495方法读取视口或本节点变换组件在当前方向的长度。
502方法按照分页方向从触点横纵坐标选取手势主轴值。
507方法按照分页方向从触点横纵坐标选取手势副轴值。
512方法把主轴拖动位移符号转换为逻辑页前后方向。
520方法按滚动方向和翻页方向计算缓冲页默认停靠位置。
528方法计算当前页在本次翻页动画离场后抵达的位置。
536方法将轴向偏移换算为节点位置并写入指定物理页。
541方法从目标物理页当前位置读取当前分页方向的坐标。
548方法构造只有分页主轴存在偏移的三维局部位置。
555方法按两次采样位移与毫秒差平滑更新主轴释放速度。
571方法保留软区内原始位移并阻尼限制超出软区的跟手距离。
585方法把边界拖动位移映射为逐渐饱和的橡皮筋距离。
594方法结合剩余距离比例与甩动速度夹取翻页动画秒数。
603方法沿目标父链确认触摸命中当前活动页的内部节点。
627方法向原始触摸目标派发一次带模拟标记的取消事件。
647方法事件直接命中分页器本身时阻止向父按钮继续传播。