如何实现按下指定按钮时,基于摇杆方向控制物体移动的代码?
摇杆+按钮控制物体移动实现(Unity)
核心逻辑
仅当编号2的按钮处于按下状态时,响应编号1摇杆的方向输入以控制物体移动;按钮松开则物体停止移动。
完整代码(C#)
将此脚本挂载到需要移动的物体上,在Inspector面板中绑定对应的摇杆和按钮组件:
using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class ControlledMovement : MonoBehaviour { [Header("UI控件引用")] public Joystick movementJoystick; // 编号1的摇杆 public Button movementButton; // 编号2的按钮 [Header("移动参数")] public float moveSpeed = 6f; private bool _isMoveAllowed = false; private void Start() { // 给按钮绑定按下/松开事件 var eventTrigger = movementButton.GetComponent<EventTrigger>() ?? movementButton.gameObject.AddComponent<EventTrigger>(); // 按下按钮时允许移动 AddTriggerEvent(eventTrigger, EventTriggerType.PointerDown, () => _isMoveAllowed = true); // 松开按钮时禁止移动 AddTriggerEvent(eventTrigger, EventTriggerType.PointerUp, () => _isMoveAllowed = false); } private void Update() { if (!_isMoveAllowed) { // 按钮未按下,停止物体移动(适配带刚体的物体) GetComponent<Rigidbody>()?.velocity = Vector3.zero; return; } // 获取摇杆的方向输入 Vector2 joystickInput = movementJoystick.Direction; // 转换为世界空间的移动方向(适配XZ平面移动) Vector3 moveDirection = new Vector3(joystickInput.x, 0, joystickInput.y).normalized; // 移动物体(直接变换位置,适配无刚体场景) transform.Translate(moveDirection * moveSpeed * Time.deltaTime, Space.World); } // 封装添加事件的工具方法 private void AddTriggerEvent(EventTrigger trigger, EventTriggerType triggerType, System.Action action) { var entry = new EventTrigger.Entry(); entry.eventID = triggerType; entry.callback.AddListener((data) => action.Invoke()); trigger.triggers.Add(entry); } }
适配说明
- 摇杆类型适配:如果使用Unity新输入系统或第三方摇杆插件,替换
movementJoystick.Direction为对应获取输入的方法即可,比如新输入系统的写法:Vector2 joystickInput = PlayerInput.current.actions["Move"].ReadValue<Vector2>(); - 物理移动优化:若物体带有
Rigidbody,建议用rb.MovePosition代替Transform.Translate,避免物理冲突:Rigidbody rb = GetComponent<Rigidbody>(); rb.MovePosition(transform.position + moveDirection * moveSpeed * Time.deltaTime); - 渐变停止效果:若需要按钮松开后物体逐渐减速,可将
_isMoveAllowed改为输入权重值,通过插值实现减速逻辑。
内容的提问来源于stack exchange,提问作者AB O1
相关产品推荐
相关产品推荐

