如何修正Realistic FPS Controller斜向移动速度异常问题?
问题解决:FPS控制器斜向移动速度异常
问题现象
使用Evolve Games的Realistic FPS Controller时,玩家斜向移动(同时按前后+左右方向键)时速度明显快于直线移动;尝试对moveDirection直接归一化后,又出现移动速度过慢的问题。
原因分析
斜向速度过快是因为两个垂直方向的移动向量相加后,向量长度变为原来的√2倍(约1.414倍)。原代码直接将输入轴乘以速度后再相加,导致斜向时实际速度是设定值的1.4倍左右。
直接归一化moveDirection会导致:即使输入轴未拉满(比如摇杆只推了一半),移动速度也会被强制拉到最大设定值,或因归一化后未正确还原速度比例,反而出现移动过慢。
修复方案
正确做法是先处理输入方向的归一化,再乘以对应速度,同时保留输入轴的幅度(比如半推摇杆时速度按比例降低)。修改Update方法中的移动计算部分:
修改前代码片段
Vector3 forward = transform.TransformDirection(Vector3.forward); Vector3 right = transform.TransformDirection(Vector3.right); isRunning = !isCrough ? CanRunning ? Input.GetKey(KeyCode.LeftShift) : false : false; vertical = canMove ? (isRunning ? RunningValue : WalkingValue) * Input.GetAxis("Vertical") : 0; horizontal = canMove ? (isRunning ? RunningValue : WalkingValue) * Input.GetAxis("Horizontal") : 0; if (isRunning) RunningValue = Mathf.Lerp(RunningValue, RuningSpeed, timeToRunning * Time.deltaTime); else RunningValue = WalkingValue; float movementDirectionY = moveDirection.y; moveDirection = (forward * vertical) + (right * horizontal);
修改后代码片段
Vector3 forward = transform.TransformDirection(Vector3.forward); Vector3 right = transform.TransformDirection(Vector3.right); isRunning = !isCrough ? CanRunning ? Input.GetKey(KeyCode.LeftShift) : false : false; // 获取原始输入轴,不提前乘速度 float rawVertical = canMove ? Input.GetAxis("Vertical") : 0; float rawHorizontal = canMove ? Input.GetAxis("Horizontal") : 0; if (isRunning) RunningValue = Mathf.Lerp(RunningValue, RuningSpeed, timeToRunning * Time.deltaTime); else RunningValue = WalkingValue; float movementDirectionY = moveDirection.y; // 构建输入方向向量,限制最大长度为1(避免斜向速度超标) Vector3 moveInput = new Vector3(rawHorizontal, 0, rawVertical); moveInput = Vector3.ClampMagnitude(moveInput, 1f); // 转换为世界空间方向并乘以当前速度 float currentSpeed = isRunning ? RunningValue : WalkingValue; moveDirection = (forward * moveInput.z) + (right * moveInput.x); moveDirection *= currentSpeed;
关键修改点
- 分离输入轴与速度计算:先获取原始输入值,不提前乘以速度。
- 使用
Vector3.ClampMagnitude限制输入向量最大长度为1:既解决斜向速度超标问题,又保留输入幅度(半推摇杆时速度按比例降低)。 - 最后将归一化后的方向向量乘以当前速度,得到正确的移动方向。
额外说明
修改后,无论直线还是斜向移动,速度都会严格等于设定的walkingSpeed或RuningSpeed,同时支持输入幅度的渐变(比如摇杆非满值时的慢速移动)。
内容的提问来源于stack exchange,提问作者Alexander Grin
相关产品推荐
相关产品推荐

