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

Unity中如何将Horizontal/Vertical轴绑定到4个触摸按钮?

Unity触摸按钮绑定控制立方体移动

现有控制立方体移动的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Movement : MonoBehaviour
{
    Vector2 Vec; 
    void Start()
    {

    }
 
    void Update()
    {
        Vec = transform.localPosition;
        Vec.x += Input.GetAxis("Horizontal") * Time.deltaTime * 20;
        Vec.y += Input.GetAxis("Vertical") * Time.deltaTime * 20;
        transform.localPosition = Vec;
    }
}

如果不想配置Input Manager,直接通过四个触摸按钮实现上下左右控制,按以下步骤操作:

1. 创建触摸UI按钮

  • 在场景中创建Canvas,在Canvas下新建4个Button,分别命名为LeftBtn、RightBtn、UpBtn、DownBtn
  • 调整按钮位置到屏幕合适区域(比如底部左右、顶部左右,或者屏幕四边),设置好按钮大小和显示文字(比如左、右、上、下)

2. 修改Movement脚本

替换原有脚本为以下代码,直接通过按钮事件控制输入值:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Movement : MonoBehaviour
{
    // 在编辑器中拖入对应的按钮
    public Button leftBtn;
    public Button rightBtn;
    public Button upBtn;
    public Button downBtn;

    private float horizontalInput;
    private float verticalInput;

    void Start()
    {
        // 绑定按钮按下/抬起/离开事件
        leftBtn.onPointerDown.AddListener(() => horizontalInput = -1f);
        leftBtn.onPointerUp.AddListener(() => horizontalInput = 0f);
        leftBtn.onPointerExit.AddListener(() => horizontalInput = 0f);

        rightBtn.onPointerDown.AddListener(() => horizontalInput = 1f);
        rightBtn.onPointerUp.AddListener(() => horizontalInput = 0f);
        rightBtn.onPointerExit.AddListener(() => horizontalInput = 0f);

        upBtn.onPointerDown.AddListener(() => verticalInput = 1f);
        upBtn.onPointerUp.AddListener(() => verticalInput = 0f);
        upBtn.onPointerExit.AddListener(() => verticalInput = 0f);

        downBtn.onPointerDown.AddListener(() => verticalInput = -1f);
        downBtn.onPointerUp.AddListener(() => verticalInput = 0f);
        downBtn.onPointerExit.AddListener(() => verticalInput = 0f);
    }
 
    void Update()
    {
        Vector2 vec = transform.localPosition;
        vec.x += horizontalInput * Time.deltaTime * 20;
        vec.y += verticalInput * Time.deltaTime * 20;
        transform.localPosition = vec;
    }
}

3. 绑定按钮到脚本

  • 选中挂载了Movement脚本的立方体对象
  • 在Inspector面板中,把场景里的四个按钮分别拖入脚本对应的leftBtn、rightBtn、upBtn、downBtn变量槽中

完成以上步骤后,运行游戏,触摸对应的按钮就能控制立方体上下左右移动,无需配置Input Manager。

内容的提问来源于stack exchange,提问作者VM- Hoss

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:37:38