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

如何实现Unity中流畅的玩家持续移动?

解决Unity玩家按住方向键持续移动的问题

你的代码卡顿且需要多次点击的原因是用了Input.GetKeyDown()——这个方法仅在按键首次按下的单帧返回true,所以每次点击只能触发一次移动。要实现按住方向键持续移动,只需把Input.GetKeyDown()替换为Input.GetKey(),后者会在按键按住的每帧都返回true。

修改后的代码如下:

void Update()
{
    if (Input.GetKey(KeyCode.LeftArrow))
    {
        transform.position += transform.right * (Time.deltaTime * 5);
    }
    if (Input.GetKey(KeyCode.RightArrow))
    {
        transform.position -= transform.right * (Time.deltaTime * 5);
    }
}

补充说明:Time.deltaTime的作用是让移动速度不受游戏帧率波动影响,保证不同性能设备上移动速度一致,这个部分可以保留。

内容的提问来源于stack exchange,提问作者Benjamin Morales Perez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:35:20