_xiaofang/xiaofang/Assets/Script/hylScripts/JoystickController.cs
2024-12-19 11:54:47 +08:00

70 lines
2.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class JoystickController : MonoBehaviour, IDragHandler, IEndDragHandler
{
public bool isDrag = false;
public RectTransform joystickBackground; // 摇杆背景
public RectTransform joystick; // 摇杆
public Camera playerCamera; // 摄像机
public float rotationSpeed = 5f; // 摄像机旋转速度
private Vector2 joystickInput = Vector2.zero;
void Start()
{
// 初始化摇杆的位置
joystick.anchoredPosition = Vector2.zero;
}
// 每帧更新摇杆的输入
void Update()
{
if (joystickInput.magnitude > 0)
{
// 根据摇杆的输入控制摄像机旋转
float horizontal = joystickInput.x;
float vertical = joystickInput.y;
// 水平旋转
playerCamera.transform.Rotate(Vector3.up, horizontal * rotationSpeed * Time.deltaTime);
// 垂直旋转
playerCamera.transform.Rotate(Vector3.left, vertical * rotationSpeed * Time.deltaTime);
}
}
// 摇杆拖动时更新摇杆位置和输入
public void OnDrag(PointerEventData eventData)
{
isDrag = true;
// 更新摇杆的位置
joystick.anchoredPosition = joystickInput;
Vector2 localPoint;
// 将触摸位置从屏幕坐标转换为UI本地坐标
RectTransformUtility.ScreenPointToLocalPointInRectangle(joystickBackground, eventData.position, eventData.pressEventCamera, out localPoint);
// 计算摇杆的输入方向
joystickInput = localPoint.normalized;
// 限制摇杆的移动范围,确保它不会超出背景的边界
if (localPoint.magnitude > joystickBackground.sizeDelta.x / 2)
{
joystickInput = localPoint.normalized * (joystickBackground.sizeDelta.x / 2);
}
}
// 摇杆松开时重置摇杆位置
public void OnEndDrag(PointerEventData eventData)
{
isDrag = false;
joystick.anchoredPosition = Vector2.zero;
joystickInput = Vector2.zero;
}
}