Unity UGUI通过摇杆joystick 控制角色移动 标准的第三人称视角手游-左侧控制移动,右侧控制视角和方向
- 效果图显示 附上demo下载地址 备注:资源是URP的,普通平台修改资源材质即可
- 代码实现
1,控制移动
// Update is called once per frame
void Update()
{
horizontal = analogLeft.localPosition.x;
vertical = analogLeft.localPosition.y;
//hor = 遥感脚本中的localPosition.x
float hor = Horizontal;
//hor = 遥感脚本中的localPosition.y
float ver = Vertical;
Vector3 direction = new Vector3(hor, 0, ver);
if (direction != Vector3.zero)
{
//控制移动
float newSpeed = Mathf.Lerp(ani.GetFloat("Speed"), 3, Time.deltaTime * 5);
ani.SetFloat("Speed", newSpeed);
//控制旋转
ani.transform.rotation = Quaternion.Lerp(ani.transform.rotation, Quaternion.LookRotation(direction), Time.deltaTime * 10);
}
else
{
//停止移动
float newSpeed = Mathf.Lerp(ani.GetFloat("Speed"), 0, Time.deltaTime * 5);
ani.SetFloat("Speed", 0);
}
}
/// <summary>
/// 当鼠标开始拖拽时
/// </summary>
/// <param name="eventData"></param>
public void OnDrag(PointerEventData eventData)
{
//获取鼠标位置与初始位置之间的向量
Vector2 oppsitionVec = eventData.position - moveBackPos;
//获取向量的长度
float distance = Vector3.Magnitude(oppsitionVec);
//最小值与最大值之间取半径
float radius = Mathf.Clamp(distance, 0, maxRadius);
//限制半径长度
analogLeft.position = moveBackPos + oppsitionVec.normalized * radius;
}
2,控制相机旋转
void RotateAroundCube()
{
float x = 0;
float y = 0;
#if !UNITY_STANDALONE_WIN
bool isright = false;
foreach (var ta in Input.touches)
{
if (ta.position.x > (Screen.width / 2))
{
if (lastpoint != Vector3.zero)
{
x = ta.position.x - lastpoint.x;
y = ta.position.y - lastpoint.y;
}
lastpoint = new Vector3(ta.position.x, ta.position.y);
isright = true;
break;
}
}
if (Input.touches.Length <= 0)
{
lastpoint = Vector3.zero;
x = 0;
y = 0;
}
if (!isright)
{
lastpoint = Vector3.zero;
x = 0;
y = 0;
}
#endif
#if UNITY_STANDALONE_WIN
if (Input.GetMouseButton(0))
{
x = Input.GetAxis("Mouse X");
y = Input.GetAxis("Mouse Y");
rotateX += x * 2f;
// Debug.Log("rotateX" + rotateX);
rotateY -= y * 2f;
// Debug.Log("rotateY" + rotateY);
}
#else
rotateX += x * 1f * Time.deltaTime;
Debug.Log("rotateX" + rotateX);
rotateY -= y * 1.1f * Time.deltaTime;
Debug.Log("rotateY" + rotateY);
#endif
//防止出现翻转现象
rotateY = Mathf.Clamp(rotateY, -30, 35);
//rotateZ += Input.GetAxis("Mouse ScrollWheel") * 5;
//rotateZ = Mathf.Clamp(rotateZ, -12, -2);
transform.position = target.transform.position +
Quaternion.Euler(rotateY, rotateX, 0) * new Vector3(0, 1, rotateZ);
transform.LookAt(target.transform);
offset = transform.position - target.position;
transform.position = offset + target.transform.position;
}
}
- demo下载地址 附上demo下载地址 备注:资源是URP的,普通平台修改资源材质即可