手势驱动的物理引擎:触控交互中的速度继承与惯性衰减数学模型 - minVelocity: 0
手势驱动的物理引擎:触控交互中的速度继承与惯性衰减数学模型
一、触控交互的"廉价感"从何而来——速度断裂与惯性缺失
在移动端应用中,列表滚动是最基础的交互。但同样是滚动,原生应用的列表丝滑流畅,Web 应用的列表却总让人觉得"拖沓"。根本原因不在于帧率——60fps 的 Web 动画已经足够流畅——而在于手指离开屏幕后的行为差异。
原生应用中,手指离开屏幕的瞬间,列表会以手指离开时的速度继续滚动,然后逐渐减速直到停止。这个"惯性滚动"的行为,让用户感知到"界面在响应我的动作"。而大量 Web 应用的实现是:手指一离开,滚动立刻停止,或者以一个固定的减速曲线停止——速度与手势速度完全无关。
这种"速度断裂"是触控交互廉价感的核心来源。用户的肌肉记忆预期"甩得越快,滚得越远",但界面没有继承手势速度,打破了物理一致性。本文将深入拆解触控交互中的速度继承与惯性衰减模型,并给出生产级的手势物理引擎实现。
二、触控物理引擎的事件-计算-渲染三层架构
flowchart TB
subgraph Input["输入层:手势事件采集"]
A[touchstart / pointerdown
记录起始位置与时间]
B[touchmove / pointermove
计算瞬时速度]
C[touchend / pointerup
输出最终速度]
end
subgraph Physics["计算层:物理引擎"]
D[速度继承
v₀ = 手指离开时的速度]
E[惯性衰减
v(t) = v₀ · e^(-λt)]
F[边界检测
过冲回弹 / 橡皮筋效果]
end
subgraph Render["渲染层:动画驱动"]
G[requestAnimationFrame
单循环调度]
H[transform: translateX/Y
合成线程渲染]
end
A -->B -->C
C -->D
D -->E
E -->F
F -->G
G -->H
style Input fill:#e3f2fd,stroke:#2196f3
style Physics fill:#e8f5e9,stroke:#4caf50
style Render fill:#fff3e0,stroke:#ff9800
三层架构的职责划分:输入层负责从原始触摸事件中提取位置和时间数据;计算层负责物理模型的求解,包括速度继承、惯性衰减和边界回弹;渲染层负责将计算结果映射到 CSS transform 属性,通过合成线程渲染避免主线程阻塞。
三、手势物理引擎的生产级实现 拼多多帮助力入口
3.1 速度采集器——从触摸事件到瞬时速度
interface VelocitySample {
position: number; // 位置(px)
timestamp: number; // 时间戳(ms)
}
class VelocityTracker {
private samples: VelocitySample[] = [];
private maxSamples = 5; // 保留最近 5 个采样点,避免过早采样干扰
/**
* 记录新的位置采样
* 在 touchmove / pointermove 事件中调用
*/
addSample(position: number, timestamp: number): void {
this.samples.push({ position, timestamp });
// 只保留最近的采样点,丢弃过旧数据
if (this.samples.length > this.maxSamples) {
this.samples.shift();
}
}
/**
* 计算当前瞬时速度
* 使用最近两个采样点的位移差除以时间差
* 返回值单位:px/ms
*/
getVelocity(): number {
if (this.samples.length < 2) return 0;
const latest = this.samples[this.samples.length - 1];
const earliest = this.samples[0];
const deltaTime = latest.timestamp - earliest.timestamp;
if (deltaTime === 0) return 0;
const deltaPosition = latest.position - earliest.position;
return deltaPosition / deltaTime;
}
/**
* 重置采样数据
* 在 touchstart / pointerdown 时调用
*/
reset(): void {
this.samples = [];
}
}
3.2 惯性衰减引擎——指数衰减模型
interface InertiaConfig {
deceleration: number; // 衰减系数 λ,值越大减速越快,推荐 0.003-0.005
minVelocity: number; // 最小速度阈值,低于此值停止动画,推荐 0.01 px/ms
maxOverscroll: number; // 最大过冲距离(px),用于橡皮筋效果
bounceStiffness: number; // 回弹弹簧刚度,推荐 0.05-0.1
}
class InertiaEngine {
private config: InertiaConfig;
private velocity: number = 0;
private position: number = 0;
private minBound: number = -Infinity;
private maxBound: number = Infinity;
private rafId: number | null = null;
private lastTimestamp: number | null = null;
private isOverscrolling: boolean = false;
constructor(config: InertiaConfig) {
this.config = config;
}
/**
* 设置滚动边界
* position 超出 [minBound, maxBound] 时触发过冲回弹
*/
setBounds(min: number, max: number): void {
this.minBound = min;
this.maxBound = max;
}
/**
* 启动惯性动画
* initialVelocity: 手指离开时的速度(px/ms)
* initialPosition: 手指离开时的位置(px)
*/
start(
initialVelocity: number,
initialPosition: number,
onUpdate: (position: number) => void,
onComplete?: () => void
): void {
// 限制最大初始速度,防止过快的甩动导致内容飞出视口
const maxVelocity = 5; // px/ms,约 300px/帧
this.velocity = Math.max(-maxVelocity, Math.min(maxVelocity, initialVelocity));
this.position = initialPosition;
this.lastTimestamp = null;
this.isOverscrolling = false;
if (this.rafId !== null) {
cancelAnimationFrame(this.rafId);
}
const step = (timestamp: number) => {
if (this.lastTimestamp === null) {
this.lastTimestamp = timestamp;
this.rafId = requestAnimationFrame(step);
return;
}
// 限制最大步长,防止切后台回来时步长过大
const dt = Math.min(timestamp - this.lastTimestamp, 32);
this.lastTimestamp = timestamp;
if (this.isOverscrolling) {
// 过冲回弹:使用弹簧模型
this.updateBounce(dt);
} else {
// 正常惯性:指数衰减
this.updateInertia(dt);
}
// 检测是否进入过冲区域
if (!this.isOverscrolling) {
if (this.position < this.minBound || this.position > this.maxBound) {
this.isOverscrolling = true;
}
}
onUpdate(this.position);
// 停止条件:速度足够小且回到边界内
const isSettled =
Math.abs(this.velocity) < this.config.minVelocity &&
this.position >= this.minBound &&
this.position <= this.maxBound;
if (isSettled) {
// 钳位到边界
this.position = Math.max(
this.minBound,
Math.min(this.maxBound, this.position)
);
onUpdate(this.position);
onComplete?.();
this.rafId = null;
return;
}
this.rafId = requestAnimationFrame(step);
};
this.rafId = requestAnimationFrame(step);
}
/**
* 指数衰减模型:v(t) = v₀ · e^(-λ·t)
* 位置更新:x(t+dt) = x(t) + v(t) · dt
*/
private updateInertia(dt: number): void {
// 指数衰减:速度乘以衰减因子
const decayFactor = Math.exp(-this.config.deceleration * dt);
this.velocity *= decayFactor;
// 更新位置
this.position += this.velocity * dt;
}
/**
* 过冲回弹:弹簧模型
* 当位置超出边界时,施加指向边界的弹簧力
*/
private updateBounce(dt: number): void {
let targetPosition: number;
if (this.position < this.minBound) {
targetPosition = this.minBound;
} else {
targetPosition = this.maxBound;
}
// 弹簧力:F = -k * (x - target)
const displacement = this.position - targetPosition;
const springForce = -this.config.bounceStiffness * displacement;
// 阻尼力:F = -c * v(阻尼系数取刚度的 1.5 倍,确保过阻尼)
const dampingForce = -this.config.bounceStiffness * 1.5 * this.velocity;
// 更新速度和位置
this.velocity += (springForce + dampingForce) * dt;
this.position += this.velocity * dt;
// 检测是否回到边界内
if (
this.position >= this.minBound &&
this.position <= this.maxBound &&
Math.abs(this.velocity) < this.config.minVelocity * 2
) {
this.isOverscrolling = false;
this.position = Math.max(
this.minBound,
Math.min(this.maxBound, this.position)
);
}
}
/** 手动中断惯性动画(用于手势接管) */
interrupt(): { position: number; velocity: number } {
if (this.rafId !== null) {
cancelAnimationFrame(this.rafId);
this.rafId = null;
}
return { position: this.position, velocity: this.velocity };
}
}
3.3 完整的手势交互控制器
class GestureScrollController {
private velocityTracker: VelocityTracker;
private inertiaEngine: InertiaEngine;
private isDragging = false;
private startPosition = 0;
private currentPosition = 0;
constructor(
private element: HTMLElement,
private scrollContainer: HTMLElement,
private onUpdate: (translateY: number) => void
) {
this.velocityTracker = new VelocityTracker();
this.inertiaEngine = new InertiaEngine({
deceleration: 0.004,
minVelocity: 0.01,
maxOverscroll: 120,
bounceStiffness: 0.08,
});
this.bindEvents();
}
private bindEvents(): void {
this.element.addEventListener('pointerdown', this.onPointerDown.bind(this));
window.addEventListener('pointermove', this.onPointerMove.bind(this));
window.addEventListener('pointerup', this.onPointerUp.bind(this));
}
private onPointerDown(e: PointerEvent): void {
this.isDragging = true;
this.startPosition = e.clientY;
this.velocityTracker.reset();
// 中断正在进行的惯性动画,获取当前状态
const state = this.inertiaEngine.interrupt();
this.currentPosition = state.position;
}
private onPointerMove(e: PointerEvent): void {
if (!this.isDragging) return;
const deltaY = e.clientY - this.startPosition;
this.startPosition = e.clientY;
// 记录速度采样
this.velocityTracker.addSample(this.currentPosition, performance.now());
// 更新位置
this.currentPosition += deltaY;
this.onUpdate(this.currentPosition);
}
private onPointerUp(_e: PointerEvent): void {
if (!this.isDragging) return;
this.isDragging = false;
// 获取手指离开时的速度
const velocity = this.velocityTracker.getVelocity();
// 计算滚动边界
const containerHeight = this.scrollContainer.clientHeight;
const contentHeight = this.element.scrollHeight;
const maxScroll = Math.max(0, contentHeight - containerHeight);
this.inertiaEngine.setBounds(-maxScroll, 0);
// 启动惯性动画,继承手势速度
this.inertiaEngine.start(
velocity,
this.currentPosition,
(position) => {
this.currentPosition = position;
this.onUpdate(position);
}
);
}
}
四、物理引擎的调参难题与性能边界
4.1 衰减系数的平台差异
不同操作系统对惯性滚动的"手感"有不同预期。iOS 的惯性滚动衰减较慢(用户甩出后滚得远),Android 的衰减较快(更"克制")。Web 应用需要根据平台动态调整衰减系数:iOS 使用 λ=0.003,Android 使用 λ=0.005。通过 navigator.userAgent 检测平台,在引擎初始化时选择对应参数。
4.2 过冲回弹的弹性感知
橡皮筋效果的弹性由 bounceStiffness 控制。值过小,回弹缓慢,用户感觉"黏滞";值过大,回弹剧烈,用户感觉"弹跳"。iOS 原生的橡皮筋效果使用临界阻尼(不振荡),建议 bounceStiffness 的阻尼比设为 1.0-1.2,避免过冲后的二次振荡。
4.3 rAF 循环的调度开销
每个手势控制器都维护一个独立的 rAF 循环。在包含多个可滚动区域的页面中(如双栏布局),同时运行的 rAF 循环可能超过 2 个。建议使用全局的 rAF 调度器,将所有动画回调合并到同一个循环中,减少帧调度开销。
4.4 不适用场景
手势物理引擎不适合桌面端的鼠标滚轮交互——鼠标滚轮的"滚动"是离散的(每次触发一个固定距离的滚动),而非连续的拖拽。对于鼠标滚轮,应使用"平滑滚动"方案(将离散的滚动事件插值为连续动画),而非惯性衰减模型。此外,在低端设备上,物理引擎的计算开销可能导致帧率下降,需要提供降级方案(关闭惯性动画,直接跟随手势位置)。
五、总结
触控交互的物理一致性,是区分"原生感"和"Web 感"的关键因素。速度继承让界面响应用户的甩动手势,惯性衰减让滚动自然减速,过冲回弹让边界状态有弹性反馈。三层架构——输入层采集速度、计算层求解物理模型、渲染层驱动 transform——将手势事件转化为物理可信的界面运动。
落地路线:先在核心滚动列表中集成 VelocityTracker 和 InertiaEngine,验证速度继承和惯性衰减的手感;再添加过冲回弹,处理边界状态;最后根据平台动态调整衰减系数,匹配 iOS 和 Android 的不同手感预期。调参过程建议使用可交互的调试面板,实时修改参数并观察效果,而非反复修改代码。