You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity同时按住多方向键时Sprite仅单方向移动如何解决

问题根源

  • 你在每一个方向判断满足后都会立刻执行timer = 0重置计时器,导致后续其他方向的判断逻辑中,timer已经不满足timer > movementDelay的条件,因此即便多键同时按下,也只有写在最前面的方向逻辑会生效。
  • 你不需要每次移动都单独判断计时器,应该先收集当前帧的输入方向,再统一判断是否满足移动间隔要求。

修复方案

先收集本次要移动的偏移量,确认满足移动间隔后再统一应用位移、重置计时器,修改后的代码如下:

public Transform timmyTransform;
private float timer = 0;
public float movementDelay;

void Update()
{
    timer += Time.deltaTime;
    // 先计算总移动偏移量
    Vector3 moveOffset = Vector3.zero;
    if (Input.GetAxis("Vertical") < 0)
    {
        moveOffset += new Vector3(0, -1, 0);
    }
    if (Input.GetAxis("Vertical") > 0)
    {
        moveOffset += new Vector3(0, 1, 0);
    }
    if (Input.GetAxis("Horizontal") < 0)
    {
        moveOffset += new Vector3(-1, 0, 0);
    }
    if (Input.GetAxis("Horizontal") > 0)
    {
        moveOffset += new Vector3(1, 0, 0);
    }

    // 有输入且满足移动间隔时才执行移动
    if (moveOffset != Vector3.zero && timer > movementDelay)
    {
        timer = 0;
        timmyTransform.position += moveOffset;
    }
}

额外优化:timmyTransform本身就是Transform类型,不需要再访问.transform属性,直接调用position即可。

内容的提问来源于stack exchange,提问作者user11718790

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:39:00