# Unity Notes之屏幕触点轨迹的平滑

• 通过屏幕点击来精确控制对应的武器光标的位置；
• 得到较为精确且平滑的、用户在屏幕拖拽移动时的拖尾效果；

1. 低速移动下的误差不能太大，否则用户不能实现精确控制；
2. 高速移动下的迟滞不能太大，否则用户感觉系统反应迟钝；

void LowPassFilter(Vector2 currentPosition, Vector2 currentVelocity, float dt)
{
if (Mathf.Approximately((currentVelocity - mFilteredVelocity).sqrMagnitude, 0))
{
mFilteredVelocity = currentVelocity;
}
else
{
mFilteredVelocity = FilterKernel(currentVelocity, mFilteredVelocity, Alpha(Vector2.one, dt));
}

if (Mathf.Approximately((currentPosition - mFilteredPosition).sqrMagnitude, 0))
{
mFilteredPosition = currentPosition;
}
else
{
Vector2 cutoffFrequency;
cutoffFrequency.x = mJitterReduction + 0.01f * mLagReduction * Mathf.Abs(mFilteredVelocity.x);
cutoffFrequency.y = mJitterReduction + 0.01f * mLagReduction * Mathf.Abs(mFilteredVelocity.y);
mFilteredPosition = FilterKernel(currentPosition, mFilteredPosition, ComputeExpSmoothingFactor(cutoffFrequency, dt));
}
}

Vector2 ComputeExpSmoothingFactor(Vector2 cutoff, float dt)
{
float tauX = 1 / (2 * Mathf.PI * cutoff.x);
float tauY = 1 / (2 * Mathf.PI * cutoff.y);
float fX = 1 / (1 + tauX / dt);
float fY = 1 / (1 + tauY / dt);
fX = Mathf.Clamp(fX, 0, 1);
fY = Mathf.Clamp(fY, 0, 1);
return new Vector2(fX, fY);
}

Vector2 FilterKernel(Vector2 current, Vector2 previous, Vector2 expFactor)
{
float x = expFactor.x * current.x + (1 - expFactor.x) * previous.x;
float y = expFactor.y * current.y + (1 - expFactor.y) * previous.y;
return new Vector2(x, y);
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：Unity Notes之屏幕触点轨迹的平滑 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)