如何计算滚动事件的滚动动量?
我知道在结束滚动的开始处必须有两个时间戳。还必须有一个“轴变化”变量,它基本上是无惯性滚动的量。
这是我当前负责结束滚动的代码:
if ((type == kMXTEnd || type == kMXTMovedOut) && _isScrolling)
{
long int finishTime = MXTimestamp();
printf("SCEnd: Ending scroll at %ld\n",finishTime-_beginTime);
/* scrollX is the change in X axis */
/* finishTime is time from touch down to touch up */
printf(" * Time: %ld ChangeX: %f\n",finishTime,scrollX);
_isScrolling = FALSE;
_originalScrollPoint = _scrollPoint;
}
是否可以为此计算“惯性加法”?就像惯性获得的额外偏移量一样,除了主滚动值外,我还可以滚动它。还是我需要获取额外的变量?
我需要这个,因为我正在编写我自己的 UI 工具包,它并不是真正基于任何东西。
最佳答案
我所做的并取得了良好的效果如下。
在每个鼠标拖动事件(或触摸事件)中,您存储速度(即移动量除以自上一帧以来的时间)和时间戳。您只需要最后一个,所以这只是两个变量。
当鼠标/触摸被释放时,检查最后一个时间戳是否足够近(我使用 0.3 秒)。如果是这样,将变量 inertialVelocity 设置为最后计算的速度;否则将其设置为 0 以防止在用户仔细选择位置时滚动。
然后在每次更新时(通过计时器或每次渲染调用,具体取决于您的渲染方式),滚动 inertialVelocity * INERTIA_SCROLL_FACTOR(我使用 0.9)并将 inertialVelocity 乘以 INERTIA_ACCELERATION(我使用 0.98)。
您可能想要添加一个阈值,以便在 inertialVelocity 变得太小时停止滚动。我使用 1 作为阈值,因为我的渲染库使用 float 作为坐标。如果坐标是积分,它会自行降为零。
要记住的一件事是 inertialVelocity 可以是正的也可以是负的,这取决于方向。
因此,在伪代码中:
OnMouseMove:
inertialVelocity = moveDistance / (now - timeOfLastEvent)
timeOfLastEvent = now
OnMouseUp:
if (now - timeSinceLastEvent > 0.3f)
inertialVelocity = 0
OnTimer/OnRender:
// timeDelta is needed only when doing this on render events, just to make
// it independent of the render speed. It is the time since the previous render
scrollPosition += inertialVelocity * INERTIA_SCROLL_FACTOR * timeDelta
inertialVelocity *= INERTIA_ACCELERATION * timeDelta
// Keep in mind that velocity can be negative as well, hence the abs
if (abs(inertialVelocity) < INERTIA_THRESHOLD)
inertialVelocity = 0
关于计算滚动惯性/动量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5833399/