Unity移动端如何通过屏幕按钮或区域控制玩家左右移动
Unity移动端玩家左右移动适配方案
你现有的脚本已经预留了Joystick变量,这里提供3种常用的实现方案,可按需选择:
方案1:使用已接入的摇杆实现移动
这是最省事的方案,直接读取摇杆水平轴数值即可,同时兼容原有键盘输入:
- 在
FixedUpdate的键盘判断逻辑外,新增摇杆输入读取:float horizontalInput = joystick.Horizontal; - 直接根据输入值施加横向力即可,无需重复写多段判断逻辑,代码更简洁:
rb.AddForce(horizontalInput * sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
方案2:使用自定义UI按钮触发移动
适合需要固定左右按键的操作逻辑:
- 在Canvas下新建两个
Button控件,分别命名为LeftBtn、RightBtn,调整位置和大小到你想要的操作区域 - 修改移动脚本,新增按键状态变量和按钮触发方法:
// 新增两个状态变量,记录左右按钮是否按下 private bool isLeftPressed; private bool isRightPressed; // 给左按钮的按下事件绑定的方法 public void OnLeftBtnDown() { isLeftPressed = true; } // 给左按钮的抬起事件绑定的方法 public void OnLeftBtnUp() { isLeftPressed = false; } // 右按钮同理 public void OnRightBtnDown() { isRightPressed = true; } public void OnRightBtnUp() { isRightPressed = false; }
- 在
FixedUpdate中新增按钮状态判断,施加对应方向的力即可 - 最后在Inspector面板中,给两个按钮添加
EventTrigger组件,分别绑定PointerDown和PointerUp事件到对应方法即可
方案3:屏幕指定区域触控触发
适合不需要显示UI按钮,点击屏幕对应区域就触发移动的需求,比如左半屏控制左移,右半屏控制右移,直接在FixedUpdate中加入触控判断逻辑:
if(Input.touchCount > 0) { Touch touch = Input.GetTouch(0); // 判断触控点在屏幕左半区还是右半区 if(touch.position.x < Screen.width / 2) { rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange); } else { rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange); } }
修改后的完整参考代码
using System.Collections.Generic; using UnityEngine; public class PlayerMovment : MonoBehaviour { public Rigidbody rb; public Joystick joystick; public float forwardForce = 2000f; public float sidewaysForce = 500f; private bool isLeftPressed; private bool isRightPressed; void FixedUpdate() { rb.AddForce(0, 0, forwardForce * Time.deltaTime); float horizontalInput = 0; // 键盘输入逻辑 if (Input.GetKey("d") || Input.GetKey("right")) { horizontalInput = 1; } if (Input.GetKey("a") || Input.GetKey("left")) { horizontalInput = -1; } // 摇杆输入逻辑,输入值大于死区时覆盖键盘输入 if(Mathf.Abs(joystick.Horizontal) > 0.1f) { horizontalInput = joystick.Horizontal; } // 按钮输入逻辑,覆盖前面的输入 if(isLeftPressed) { horizontalInput = -1; } if(isRightPressed) { horizontalInput = 1; } // 统一施加横向力 rb.AddForce(horizontalInput * sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange); if (rb.position.y < -1f) { FindObjectOfType<GameManager>().EndGame(); } } public void OnLeftBtnDown() => isLeftPressed = true; public void OnLeftBtnUp() => isLeftPressed = false; public void OnRightBtnDown() => isRightPressed = true; public void OnRightBtnUp() => isRightPressed = false; }
内容的提问来源于stack exchange,提问作者TomerGamerTV
相关产品推荐
相关产品推荐

