using System.Collections;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.OnScreen;
using UnityEngine.Serialization;
using UnityEngine.UIElements;
public class TestJoyListener : OnScreenControl
{
private Vector2 PointInitialPos;
private Vector2 PointPos;
private Vector2 DragPos;
/// <summary>
/// The distance from the onscreen control's center of origin, around which the control can move.
/// </summary>
public float movementRange
{
get => m_MovementRange;
set => m_MovementRange = value;
}
[FormerlySerializedAs("movementRange")]
[SerializeField]
[Min(0)]
private float m_MovementRange = 50;
[InputControl(layout = "Vector2")]
[SerializeField]
private string m_ControlPath;
private Vector3 m_StartPos;
private Coroutine _corMove;
protected override string controlPathInternal
{
get => m_ControlPath;
set => m_ControlPath = value;
}
public void Init()
{//CityTestWnd.Ins.PointUI是可拖动的摇杆,自己更改
PointInitialPos = CityTestWnd.Ins.PointUI.transform.position;
CityTestWnd.Ins.PointUI.RegisterCallback<PointerDownEvent>(OnPointerDown);
}
void OnPointerDown(PointerDownEvent Evt)
{
Vector2 mousePosition = Mouse.current.position.ReadValue();
PointPos = RuntimePanelUtils.ScreenToPanel(CityTestWnd.Ins.PointUI.panel, new Vector2(mousePosition.x, Screen.height - mousePosition.y));
DragPos = PointPos - PointInitialPos;
_corMove=StartCoroutine("Move");
}
IEnumerator Move()
{
while (Mouse.current.leftButton.isPressed)
{
//在这里处理按下鼠标并拖拽时的操作
Vector2 mousePosition = Mouse.current.position.ReadValue();
PointPos = RuntimePanelUtils.ScreenToPanel(CityTestWnd.Ins.PointUI.panel, new Vector2(mousePosition.x, Screen.height - mousePosition.y));
PointPos.x -= DragPos.x;
PointPos.y -= DragPos.y;
PointPos = Vector2.ClampMagnitude(PointPos, m_MovementRange);
CityTestWnd.Ins.PointUI.transform.position =PointPos;//panel的原点在左上,和正常的screen坐标是反着的,y轴要翻过来
var newPos = new Vector2(PointPos.x / movementRange, -PointPos.y / movementRange);
SendValueToControl(newPos);
yield return null;
}
//在这里处理松开鼠标时的操作
CityTestWnd.Ins.PointUI.transform.position = PointInitialPos;
SendValueToControl(Vector2.zero);
}
}
代码先贴上,利用的inputSystem的地方很简单,继承下OnScreenControl,就挂在panel下面,在适当的地方用SendValueToControl(Pos);给Input传过去数据就成,然后在界面选取所需要适配的控制器(一般手机屏幕选取的是LeftStick[Gamepad])。最后别忘了在场景里有EventSystem。
PS:谁有成熟的UITOOKIT手游解决方案别忘了私我,我可以有偿购买。 UI Tookit的简易摇杆-优快云博客