using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class JoyStick : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
[Header("摇杆移动半径")]
public float joyStickRadius = 45;
[Header("移动速度")]
public float speed = 3f;
private CharacterController player;
/// <summary>
/// 摇杆初始位置
/// </summary>
private Vector3 originPos;
/// <summary>
/// 拖动距离
/// </summary>
private float distance;
/// <summary>
/// 移动向量
/// </summary>
private Vector3 moveDir;
/// <summary>
/// 圆心指向鼠标位置的方向向量
/// </summary>
private Vector3 dir;
/// <summary>
/// 上一帧的鼠标坐标
/// </summary>
private Vector3 previoursMousePosition;
private void Awake()
{
player = GameObject.FindWithTag("Player").GetComponent<CharacterController>();
}
private void Start()
{
originPos = transform.position;
}
private void Update()
{
PlayerControl();
}
public void OnBeginDrag(PointerEventData eventData)
{
// 存储拖拽第一帧的鼠标坐标
previoursMousePosition = Input.mousePosition;
}
public void OnDrag(PointerEventData eventData)
{
// 求移动向量
moveDir = Input.mousePosition - previoursMousePosition;
// 保存当前帧的鼠标坐标,提供给下一帧进行运算
previoursMousePosition = Input.mousePosition;
// 求方向向量
dir = Input.mousePosition - originPos;
// 计算鼠标与原点的距离
// distance = Vector3.Distance(Input.mousePosition, originPos);
distance = dir.magnitude;
if (distance<joyStickRadius)
{
transform.position = Input.mousePosition;
}
else
{
// 求圆心指向摇杆位置的方向向量
transform.position = dir.normalized * joyStickRadius + originPos;
}
}
public void OnEndDrag(PointerEventData eventData)
{
// 摇杆回归原始位置
transform.position = originPos;
// 方向向量归零
dir = Vector3.zero ;
moveDir = Vector3.zero;
}
public void PlayerControl()
{
//player.position += new Vector3(dir.x,0,dir.y).normalized * Time.deltaTime *
speed;
// 一般使用SimpleMove
player.SimpleMove(new Vector3(dir.x, 0, dir.y).normalized * Time.deltaTime *
speed);
//if (moveDir.magnitude == 0)
//{
// player.SimpleMove(new Vector3(dir.x, 0, dir.y).normalized * Time.deltaTime
* speed);
//}
//else
//{
// player.SimpleMove(new Vector3(moveDir.x, 0, moveDir.y).normalized *
Time.deltaTime * speed);
//}
}
}