如何编写函数实现turnRadius达±0.65后指数趋极并映射为sprite水平位置
实现代码
// 可调参数,按需修改 const THRESHOLD = 0.65; // 触发指数过渡的阈值 const EXPONENT = 2; // 指数曲线曲率,数值越大过渡越陡峭 const MAX_POS = 275; const MIN_POS = 0; const MID_POS = (MAX_POS + MIN_POS) / 2; // 也就是137.5 let turnRadius = user.input; let spriteHorizontalPosition; // 阈值点对应的位置,保证区间衔接无跳变 const rightThresholdPos = (1 - THRESHOLD) * MID_POS; // turnRadius=0.65对应48.125 const leftThresholdPos = MAX_POS - rightThresholdPos; // turnRadius=-0.65对应226.875 if (turnRadius >= THRESHOLD) { // 右侧阈值区间:指数衰减到最小位置0 const normalized = (turnRadius - THRESHOLD) / (1 - THRESHOLD); const curve = Math.pow(normalized, EXPONENT); spriteHorizontalPosition = rightThresholdPos - curve * rightThresholdPos; } else if (turnRadius <= -THRESHOLD) { // 左侧阈值区间:指数增长到最大位置275 const normalized = (Math.abs(turnRadius) - THRESHOLD) / (1 - THRESHOLD); const curve = Math.pow(normalized, EXPONENT); spriteHorizontalPosition = leftThresholdPos + curve * (MAX_POS - leftThresholdPos); } else { // 中间区间保持原有线性映射,操作跟手性不受影响 spriteHorizontalPosition = (turnRadius * -1 + 1) * MID_POS; } // 边界兜底,避免极端输入超出范围 spriteHorizontalPosition = Math.max(MIN_POS, Math.min(MAX_POS, spriteHorizontalPosition)); playerSprite.transform.x = spriteHorizontalPosition;
参数调整说明
EXPONENT为曲线曲率控制参数:- 设为2是平方曲线,过渡相对平缓
- 设为3是三次方曲线,前期变化慢、后期增速快,更贴近“达到阈值后快速到极值”的效果
- 数值越大,曲线越陡,越接近原有直接切到极值的效果,可根据实际操作手感调整
内容的提问来源于stack exchange,提问作者Zurupupz
相关产品推荐
相关产品推荐

